#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
generate_plate_qr.py

Companion to export_blocks_to_json_and_qr.py.
That script intentionally SKIPS 'Shrimp on a plate' and
'Shrimp on a plate (Customer View)' stages. This script generates
QR codes for exactly those skipped stages, using the same URL
scheme, filename convention, and QR styling, so the full set of
QR codes (including plate/customer-view) is complete and consistent.

Output: static/qrcodes/<species>/<uid>.png  (same folder as the main set)
Also writes: static/json/plate_export_index.json (summary)
"""

import os
import json
import re
import sys

# --- CONFIGURATION (must match export_blocks_to_json_and_qr.py) ---
from config import PUBLIC_BASE_URL

BASE_URL = PUBLIC_BASE_URL
QR_PATH_PREFIX = "/static/qrcodes"
JSON_PATH_PREFIX = "/static/json"

def safe_filename(s):
    if not s:
        return "unknown"
    s = re.sub(r"\s+", "_", str(s).strip())
    s = re.sub(r"[^A-Za-z0-9_\-\.]", "", s)
    return s[:200]

def ensure_dir(p):
    if not os.path.exists(p):
        os.makedirs(p, exist_ok=True)

def print_banner(title):
    print("\n" + "=" * 70)
    print("🍤 " + title)
    print("=" * 70)

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
if PROJECT_ROOT not in sys.path:
    sys.path.insert(0, PROJECT_ROOT)

try:
    import blockchain_logic
except Exception as e:
    print("❌ ERROR: cannot import blockchain_logic.py:", e)
    raise SystemExit(1)

try:
    import qrcode
except Exception:
    print("⚠️  qrcode library missing. Run: pip install qrcode[pil]")
    raise SystemExit(1)

species_map = {
    "vannamei": getattr(blockchain_logic, "LINEAGE_P_VANNAMEI", []),
    "monodon": getattr(blockchain_logic, "LINEAGE_P_MONODON", []),
    "indicus": getattr(blockchain_logic, "LINEAGE_P_INDICUS", []),
    "vannamei_2025": getattr(blockchain_logic, "LINEAGE_XLSX_2025", []),
}

out_json_base = os.path.join(PROJECT_ROOT, "static", "json")
out_qr_base = os.path.join(PROJECT_ROOT, "static", "qrcodes")
ensure_dir(out_json_base)
ensure_dir(out_qr_base)

export_index = {}

print_banner("CIBA Blockchain Export Tool — Plate/Customer-View QR Generator")

for species_key, lineage in species_map.items():
    print_banner(f"Processing {species_key.upper()} (plate + customer-view stages)")
    export_index[species_key] = {"count": 0, "files": []}

    qr_species_dir = os.path.join(out_qr_base, species_key)
    ensure_dir(qr_species_dir)

    # 🔹 ONLY keep Shrimp on a plate & Customer View (inverse of the main script's filter)
    plate_lineage = []
    for blk in lineage:
        stage = str(blk.get("Stage") or blk.get("stage") or "").lower()
        if "shrimp on a plate" in stage or "customer view" in stage:
            plate_lineage.append(blk)

    if not plate_lineage:
        print(f"⚠️ No plate/customer-view blocks found for {species_key}")
        continue

    for block in plate_lineage:
        trans_data = block.get("TransactionData") or block.get("data") or block
        uid = (
            trans_data.get("Unique Blockchain ID")
            or trans_data.get("Unique Secondary ID")
            or trans_data.get("Unique ID")
            or trans_data.get("parent_batch_id")
            or trans_data.get("ID")
            or trans_data.get("id")
        )
        if not uid:
            print(f"⚠️ Skipping block with no UID: {block.get('Stage') or block.get('stage')}")
            continue

        stage_name = block.get("Stage") or block.get("stage") or "Unknown"
        qr_url = f"{BASE_URL}/block_by_id/{species_key}/{uid}"

        try:
            qr = qrcode.QRCode(
                version=None, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4
            )
            qr.add_data(qr_url)
            qr.make(fit=True)
            img = qr.make_image(fill_color="black", back_color="white")
            qr_fname = safe_filename(uid) + ".png"
            img.save(os.path.join(qr_species_dir, qr_fname))
            export_index[species_key]["count"] += 1
            export_index[species_key]["files"].append(qr_fname)
            print(f"   🔲 QR: {qr_fname} ({stage_name}) → {qr_url}")
        except Exception as e:
            print(f"⚠️  QR generation failed for {uid}: {e}")

# --- Write Summary ---
index_path = os.path.join(out_json_base, "plate_export_index.json")
with open(index_path, "w", encoding="utf-8") as f:
    json.dump(export_index, f, indent=2, ensure_ascii=False)
print(f"\n📄 Saved: {index_path}")

print_banner("✅ Plate/Customer-View QR Generation Complete")
total = sum(v["count"] for v in export_index.values())
print(f"📦 Total plate/customer-view QR codes generated: {total}")
