#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Clean Export Script (v2025.10)
Removes 'Shrimp on a plate' and 'Customer View' stages before export.
Exports clean JSONs and QR codes for all remaining blocks.
"""

import os
import json
import re
import sys

# --- CONFIGURATION ---
GENERATE_QR = True
from config import PUBLIC_BASE_URL

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

# --- Helper functions ---
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)

# --- Import Blockchain Logic ---
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)

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)

# --- QR Setup ---
qr_module = None
if GENERATE_QR:
    try:
        import qrcode
        qr_module = qrcode
        print("✅ QR generation enabled.")
    except Exception:
        print("⚠️  qrcode library missing. Run: pip install qrcode[pil]")
        GENERATE_QR = False

# --- MAIN LOGIC ---
export_index = {}
block_mapping = {}

print_banner("CIBA Blockchain Export Tool — Clean Version")

for species_key, lineage in species_map.items():
    print_banner(f"Processing {species_key.upper()}")
    export_index[species_key] = {"count": 0, "files": [], "qr_codes": [], "block_mapping": {}}
    block_mapping[species_key] = {}

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

    # 🔹 Filter out Shrimp on a plate & Customer View
    filtered_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:
            print(f"⏩ Skipping '{blk.get('Stage', 'Unknown')}'")
            continue
        filtered_lineage.append(blk)

    if not filtered_lineage:
        print(f"⚠️ No valid blocks found for {species_key}")
        continue

    for idx, block in enumerate(filtered_lineage, start=1):
        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")
            or f"{species_key}_block_{idx}"
        )

        filename = safe_filename(uid) + ".json"
        fpath = os.path.join(species_dir, filename)

        block_mapping[species_key][str(uid)] = {
            "index": idx,
            "filename": filename,
            "stage": block.get("Stage") or block.get("stage") or f"Block {idx}",
        }

        try:
            with open(fpath, "w", encoding="utf-8") as f:
                json.dump(block, f, indent=2, ensure_ascii=False)
            print(f"✅ Exported Block {idx}: {filename}")
        except Exception as e:
            print(f"❌ Failed to save {filename}: {e}")
            continue

        export_index[species_key]["count"] += 1
        export_index[species_key]["files"].append(filename)

        if GENERATE_QR:
            qr_url = f"{BASE_URL}/block_by_id/{species_key}/{uid}"
            try:
                qr = qr_module.QRCode(
                    version=None, error_correction=qr_module.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]["qr_codes"].append(qr_fname)
                print(f"   🔲 QR: {qr_fname} → {qr_url}")
            except Exception as e:
                print(f"⚠️  QR generation failed for {uid}: {e}")

# --- Write Summary Files ---
index_path = os.path.join(out_json_base, "export_index.json")
mapping_path = os.path.join(out_json_base, "block_mapping.json")

with open(index_path, "w", encoding="utf-8") as f:
    json.dump(export_index, f, indent=2, ensure_ascii=False)
print(f"📄 Saved: {index_path}")

with open(mapping_path, "w", encoding="utf-8") as f:
    json.dump(block_mapping, f, indent=2, ensure_ascii=False)
print(f"📄 Saved: {mapping_path}")

print_banner("✅ Export Complete")
total_blocks = sum(v["count"] for v in export_index.values())
print(f"📦 Total blocks exported: {total_blocks}")

