# -*- coding: utf-8 -*-
"""
ICE Educational V5.0 (Jun 2026) — parse do resumo + benchmark educacional contra o KBOB v9.

USO EDUCACIONAL/COMPARATIVO (licença ICE Educational). O pipeline comercial não usa estes valores.

Outputs:
  epd/ice_summary.json     — todos os registos {secao, material, kgco2e_por_kg, dqi}
  epd/ICE-BENCHMARK.md     — comparação ICE vs KBOB p/ materiais comuns (THG/KBOB por kg)
Uso:  py parse_ice.py
"""
import io
import json
import os
import re
import warnings

import openpyxl

warnings.filterwarnings("ignore")
HERE = os.path.dirname(os.path.abspath(__file__))

# ---------------------------------------------------------------- ICE
def parse_ice():
    wb = openpyxl.load_workbook(os.path.join(HERE, "raw", "ICE DB Educational V5.0 - Jun 2026.xlsx"),
                                read_only=True, data_only=True)
    ws = wb["ICE Summary"]
    rows = list(ws.iter_rows(values_only=True))
    out, pending, section = [], None, ""
    for r in rows:
        c5 = str(r[5]).strip() if len(r) > 5 and r[5] is not None else ""
        c6 = r[6] if len(r) > 6 else None
        if isinstance(c6, (int, float)):
            out.append({"secao": section, "material": c5, "kgco2e_por_kg": round(float(c6), 6),
                        "dqi": round(r[10], 3) if len(r) > 10 and isinstance(r[10], (int, float)) else None})
            continue
        c6s = str(c6).strip() if c6 is not None else ""
        if c5.lower().startswith("materials") and c6s.lower().startswith("embodied"):
            if pending:
                section = pending
                pending = None
            continue
        if c5 and not c6s and len(c5) < 40 and not c5.lower().startswith(("ice", "note", "introduction", "materials covered")):
            pending = c5
    return out

# ---------------------------------------------------------------- KBOB
def kbob_thg_column(rows):
    """colunas THG do KBOB v9 (verificado 2026-09-03): col 25=Total, col 26=Herstellung(A1-A3), col 27=Entsorgung (kg CO2-eq)."""
    return 25, 26

def parse_kbob():
    wb = openpyxl.load_workbook(os.path.join(HERE, "epd", "kbob_v9.xlsx"), read_only=True, data_only=True)
    ws = wb["Baumaterialien Matériaux"]
    rows = list(ws.iter_rows(values_only=True))
    tot, fab = kbob_thg_column(rows)
    items = []
    pat = re.compile(r"^\d{2}(\.\d+)*$")
    for r in rows:
        idv = str(r[0]).strip() if r[0] is not None else ""
        if not pat.match(idv) or "." not in idv:
            continue
        nome = str(r[2] or "").strip()
        unidade = str(r[6] or "").strip() if r[6] else ""
        thg_fab = r[fab] if fab is not None and fab < len(r) else None
        thg_tot = r[tot] if tot is not None and tot < len(r) else None
        items.append({"id": idv, "nome": nome, "unidade": unidade,
                      "thg_fabrico": float(thg_fab) if isinstance(thg_fab, (int, float)) else None,
                      "thg_total": float(thg_tot) if isinstance(thg_tot, (int, float)) else None})
    return items, tot, fab

# ---------------------------------------------------------------- benchmark
PARES = [
    ("Betão estrutural (geral)", r"Hochbaubeton", r"^General$", "Strength"),
    ("Aço — varão, média UK (BF)", r"Armierungsstahl", r"Steel, Rebar$", "Steel"),
    ("Aço — varão, EAF reciclado", r"Armierungsstahl", r"recycled, Europe EAF", "Steel"),
    ("Madeira maciça resinoso (s/ armaz. carbono)", r"Massivholz Fichte", r"Softwood - No Carbon", "carbon"),
    ("Lã de vidro (isolamento)", r"Glaswolle$", r"Glass Wool", "Insulation"),
    ("Tijolo cerâmico comum", r"Backstein$", r"General \(Common Brick\)", "Bricks"),
]

def pick(items, rx):
    for it in items:
        if re.search(rx, it["nome"], re.I):
            return it
    return None

def pick_ice(ice, rx, sec_hint):
    for it in ice:
        if sec_hint.lower() in it["secao"].lower() and re.search(rx, it["material"], re.I):
            return it
    return None

def main():
    ice = parse_ice()
    with io.open(os.path.join(HERE, "epd", "ice_summary.json"), "w", encoding="utf-8") as f:
        json.dump(ice, f, ensure_ascii=False, indent=1)
    secs = {}
    for it in ice:
        secs.setdefault(it["secao"], 0); secs[it["secao"]] += 1
    print(f"ICE: {len(ice)} materiais em {len(secs)} secções")
    for s, n in sorted(secs.items(), key=lambda x: -x[1]):
        print(f"   {s[:44]:44} {n}")

    kb, tot, fab = parse_kbob()
    print(f"\nKBOB: {len(kb)} itens · colunas THG: total={tot} fabrico={fab}")

    lines = ["# ICE vs KBOB — benchmark educacional (2026-09-03)\n",
             "**Licença:** ICE Educational V5.0 (Jun 2026) — uso educacional/comparativo; "
             "KBOB v9 é público. **Não usar ICE em trabalho comercial.**\n",
             "ICE = kg CO2e/kg (cradle-to-gate). KBOB = THG por unidade declarada (kg quando indicado);",
             "comparação por kg, fabrico (A1–A3 ≈ 'Herstellung').\n",
             "| material | ICE (kgCO2e/kg) | KBOB (kgCO2e/kg) | diferença | nota |", "|---|---|---|---|---|"]
    print()
    for label, krx, irx, isec in PARES:
        k = pick(kb, krx)
        i = pick_ice(ice, irx, isec)
        kv = k["thg_fabrico"] if (k and k["thg_fabrico"] is not None and k["unidade"].lower() == "kg") else None
        iv = i["kgco2e_por_kg"] if i else None
        note = ""
        if k and k["unidade"].lower() != "kg":
            note = f"KBOB unidade={k['unidade']} — valor não por kg"
        if kv is not None and iv is not None:
            diff = f"{100*(iv-kv)/kv:+.0f}%"
        else:
            diff = "—"
        lines.append(f"| {label} | {iv if iv is not None else '—'} {('<i>'+i['material'][:40]+'</i>') if i else ''} "
                     f"| {round(kv,4) if kv is not None else '—'} {('<i>'+k['nome'][:40]+'</i>') if k else ''} "
                     f"| {diff} | {note} |")
        print(f"  {label:34} ICE={iv}  KBOB={round(kv,4) if kv is not None else None}  {diff}")
    with io.open(os.path.join(HERE, "epd", "ICE-BENCHMARK.md"), "w", encoding="utf-8") as f:
        f.write("\n".join(lines) + "\n\nFontes: raw/ICE DB Educational V5.0 - Jun 2026.xlsx · epd/kbob_v9.xlsx (Ökobilanzdaten im Baubereich V9.0)\n")
    print("\n→ epd/ICE-BENCHMARK.md")

if __name__ == "__main__":
    main()
