"""Merge extract/*.json (2026 periods) and extract_2025/*.json (2025 periods) into normalized.json (ticker -> periods -> metric -> {value,source,...}).
Also merges verify/verify_results.json (blind second pass) into a per-input confidence flag."""
import json, glob, os, sys
# Working folder: COST_DIR, else the folder of this script (reproducibility fix 2026-11-15: a hard-coded build path was replaced; logic unchanged)
SP=os.environ.get("COST_DIR") or os.path.dirname(os.path.abspath(__file__))
FIELDS=["btc_mined","btc_mining_revenue","total_revenue","direct_cost_btc_gross","direct_cost_definition",
        "curtailment_dr_credits","hosting_third_party_cost","da_consolidated","da_btc_segment","sga_reported","sbc_total","sbc_in_sga",
        "interest_expense_pnl","interest_income","cash_interest_paid_3m","cash_interest_paid_ytd","impairment","restructuring_other_nonrecurring",
        "reported_cost_to_mine_ex_da_per_btc","reported_cost_to_mine_incl_da_per_btc","reported_energy_cost_per_btc","reported_other_cost_metric",
        "hashrate_avg_operating_ehs","hashrate_end_deployed_ehs","power_mw_operating","fleet_efficiency_jth","power_cost_per_kwh","mwh_consumed",
        "btc_holdings_end","btc_sold","btc_sale_proceeds","avg_btc_price_realized_or_production_value","pool_fee_treatment","ppe_net","net_income","revenue_by_segment"]
norm={}
# Incremental release: start from the previously published inputs (base_inputs.json = normalized.json of the prior release) and add new periods
BASE=f"{SP}/base_inputs.json"; NEW_PERIODS=set()
if os.path.exists(BASE):
    norm=json.load(open(BASE)); print("base inputs:",os.path.basename(BASE),"| tickers",len(norm))
def ingest(fn):
    d=json.load(open(fn)); t=d["ticker"]
    norm.setdefault(t,{"entity":d.get("entity"),"fye":d.get("fye"),"periods":{},"ai_hpc_context":None,"extraction_notes":[]})
    if d.get("entity"): norm[t]["entity"]=d.get("entity")
    if d.get("fye"): norm[t]["fye"]=d.get("fye")
    if d.get("ai_hpc_context") and not norm[t]["ai_hpc_context"]: norm[t]["ai_hpc_context"]=d.get("ai_hpc_context")
    norm[t]["extraction_notes"]+= (d.get("extraction_notes") or [])
    for per,pd in d["periods"].items():
        m=pd.get("metrics",{})
        row={"form":pd.get("form"),"accession":pd.get("accession"),"filing_date":pd.get("filing_date"),"url":pd.get("url"),"fiscal_label":pd.get("fiscal_label"),"caveats":pd.get("caveats",[]),"basis":pd.get("basis") or pd.get("reporting_basis")}
        for f in FIELDS:
            x=m.get(f)
            if isinstance(x,dict):
                row[f]={"value":x.get("value"),"source":x.get("source"),"definition":x.get("definition"),"derivation":x.get("derivation"),
                        "components":x.get("components"),"netted_in_direct_cost":x.get("netted_in_direct_cost"),"note":x.get("note")}
            else: row[f]={"value":x,"source":None}
        row["_extra"]={k:v for k,v in m.items() if k not in FIELDS}
        norm[t]["periods"][per]=row; NEW_PERIODS.add((t,per))
for fn in sorted(glob.glob(f"{SP}/extract/*.json")): ingest(fn)
for fn in sorted(glob.glob(f"{SP}/extract_2025/*.json")): ingest(fn)
for fn in sorted(glob.glob(f"{SP}/extract_q3/*.json")): ingest(fn)

# verification merge
vr_path=f"{SP}/verify/verify_results.json"
conf_stats={"XBRL":0,"TEXT-2x":0,"TEXT-1x":0,"MISMATCH":0,"NOT_FOUND":0}
if True:
    vr=json.load(open(vr_path)) if os.path.exists(vr_path) else []
    vmap={(r["ticker"],r["period"],r["metric"]):r for r in vr}
    for t,c in norm.items():
        for per,p in c["periods"].items():
            if os.path.exists(BASE) and (t,per) not in NEW_PERIODS: continue   # keep the published confidence flags of prior periods
            for f in FIELDS:
                x=p.get(f)
                if not isinstance(x,dict) or not isinstance(x.get("value"),(int,float)) or isinstance(x.get("value"),bool): continue
                src=(x.get("source") or "").lower()
                flag="XBRL" if src.startswith("xbrl") and not x.get("derivation") else "TEXT-1x"
                r=vmap.get((t,per,f))
                if r is not None:
                    v2=r.get("value")
                    if isinstance(v2,(int,float)):
                        tol=max(abs(x["value"])*0.005, 1.0 if abs(x["value"])<1000 else 1000.0)
                        if abs(v2-x["value"])<=tol: flag="XBRL" if flag=="XBRL" else "TEXT-2x"
                        else:
                            # definitional ambiguity: verifier listed our figure among its candidates (different definition, same filing)
                            alt=[c for c in (r.get("candidates") or []) if isinstance(c,dict) and isinstance(c.get("value"),(int,float)) and abs(c["value"]-x["value"])<=tol]
                            if alt:
                                flag="XBRL" if flag=="XBRL" else "TEXT-2x"; x["verify_alt"]=alt[0].get("definition"); x["verify_primary"]=v2; conf_stats["via_candidate"]=conf_stats.get("via_candidate",0)+1
                            else: flag="MISMATCH"; x["verify_value"]=v2; x["verify_quote"]=(r.get("quote") or "")[:200]; x["verify_candidates"]=r.get("candidates")
                    elif r.get("confidence")=="NOT_FOUND": flag = flag if flag=="XBRL" else "TEXT-1x"
                x["confidence"]=flag
                conf_stats[flag]=conf_stats.get(flag,0)+1
json.dump(norm,open(f"{SP}/normalized.json","w"),indent=1,default=str)
print("new periods ingested:",sorted(NEW_PERIODS))
print("tickers:",sorted(norm), "| periods:",sorted({p for c in norm.values() for p in c["periods"]}), "| confidence:",conf_stats)
