#!/usr/bin/env python3
"""Unit-normalization + anomaly-flagging pass over Scope 1/2/3 emissions.

Why this exists: BRSR XBRL filers are free to tag unitRef as tCO2e, ktCO2e,
or MtCO2e -- observed all three in this dataset (Counter: tCO2e=26, MtCO2e=21,
ktCO2e=1 for scope1 alone). At least one filer (Reliance) has a raw value
that is physically impossible under its own tagged unit (36,350,070 MtCO2e
= 36.35 billion tonnes, more than India's entire national emissions).
This script normalizes to tCO2e using the tagged unit, then flags anything
that still looks physically implausible for manual PDF verification -- it
does NOT silently "fix" a mistagged unit. Nothing here is published until
cross-checked against a primary source.
"""
import csv
from pathlib import Path

DATA = Path(__file__).resolve().parent.parent / "data"
UNIT_TO_TONNES = {"tCO2e": 1, "ktCO2e": 1_000, "MtCO2e": 1_000_000, "": None}

# Independently-read reference points (from research/brsr-primer.md, read
# directly off company PDFs in an earlier session -- NOT derived from this
# pipeline) used to sanity-check the normalization, not to calibrate it.
REFERENCE = {
    "RELIANCE": {"scope1_tco2e": 36.46e6, "scope2_tco2e": 1.47e6},  # FY24-25, primer
    "TATASTEEL_scope3_PY": 23e6,  # FY24-25 Scope3, primer (cross-checked against this
                                    # filing's own DPYMain context separately)
}


def to_tonnes(value, unit):
    if not value or unit not in UNIT_TO_TONNES or UNIT_TO_TONNES[unit] is None:
        return None
    try:
        return float(value.replace(",", "")) * UNIT_TO_TONNES[unit]
    except ValueError:
        return None


def main():
    rows = list(csv.DictReader(open(DATA / "brsr_nifty50.csv")))
    out = []
    flags = []
    for r in rows:
        rec = {"symbol": r["symbol"], "company": r["company"]}
        for scope in ("scope1_tco2e", "scope2_tco2e", "scope3_tco2e"):
            tonnes = to_tonnes(r[scope], r[scope + "_unit"])
            rec[scope + "_normalized_t"] = tonnes
            # crude physical-plausibility bound: no single Indian company's
            # Scope 1+2 should exceed ~1/3 of India's total national GHG
            # emissions (~3.9 GtCO2e/yr per UNFCCC/NDC filings) -- generous
            # bound deliberately, this is a flag-for-review, not a hard fail
            if tonnes and tonnes > 1.3e9:
                flags.append(f"{r['symbol']}: {scope} normalizes to {tonnes/1e6:.1f} Mt "
                              f"under tagged unit '{r[scope+'_unit']}' -- exceeds plausible "
                              f"bound, likely UNIT-TAGGING ERROR in filer's own XBRL. "
                              f"Raw value {r[scope]} read as tonnes = {float(r[scope].replace(',','')) / 1e6:.2f} Mt.")
        out.append(rec)

    with open(DATA / "unit_check.csv", "w", newline="") as fh:
        w = csv.DictWriter(fh, fieldnames=list(out[0].keys()))
        w.writeheader()
        w.writerows(out)

    print(f"normalized {len(out)} companies -> data/unit_check.csv")
    print(f"\n{len(flags)} FLAGGED for manual PDF verification (not published as-is):")
    for f in flags:
        print(" -", f)

    # cross-check against primer reference figures
    ril = next(r for r in out if r["symbol"] == "RELIANCE")
    ril_raw_as_tonnes = float(rows[[r["symbol"] for r in rows].index("RELIANCE")]
                               ["scope1_tco2e"].replace(",", ""))
    print(f"\nRELIANCE Scope1 tagged-unit-normalized: {ril['scope1_tco2e_normalized_t']/1e6 if ril['scope1_tco2e_normalized_t'] else None} Mt")
    print(f"RELIANCE Scope1 raw-value-as-tonnes:     {ril_raw_as_tonnes/1e6:.2f} Mt")
    print(f"RELIANCE Scope1 primer (independent PDF read, FY24-25): {REFERENCE['RELIANCE']['scope1_tco2e']/1e6:.2f} Mt")
    print("-> raw-value-as-tonnes matches the independent primer figure; the "
          "MtCO2e unitRef tag on RIL's Scope1 fact appears to be a filer-side "
          "tagging error. DO NOT trust unitRef blindly for cross-company "
          "comparison -- flag any company with a tagged-unit result outside "
          "physical plausibility and re-derive from raw value + PDF check.")


if __name__ == "__main__":
    main()
