"""Build and reconcile source-bound current poll strength metadata."""
import csv
import hashlib
import json
import math
import sys
from collections import defaultdict
from datetime import date, datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
A = ROOT / "audit/forecast_refresh_2026-11-02"
OUT_DIR = Path(__file__).resolve().parent
OUT = OUT_DIR / "current_metadata.csv"
RECEIPT = OUT_DIR / "validation/current_metadata_validation.json"
CUTOFF = date(2026, 11, 2)
ISSUE_HORIZON = 1
RELEASE_LAG = 7
P = ROOT / "audit/pollster_repair_2026-10-27"
TOL = 1e-8


def read(path):
    with Path(path).open(encoding="utf-8-sig", newline="") as f:
        return list(csv.DictReader(f))


def num(x):
    try:
        if x is None or str(x).strip() == "":
            return None
        v = float(x)
        return v if math.isfinite(v) else None
    except (TypeError, ValueError):
        return None


def day(x):
    if isinstance(x, date):
        return x
    for fmt in ("%Y-%m-%d", "%m/%d/%y", "%m/%d/%Y"):
        try:
            return datetime.strptime(str(x).strip()[:10], fmt).date()
        except (ValueError, TypeError):
            pass
    return None


def weighted_mean(values, weights):
    total = sum(weights)
    return sum(v * w for v, w in zip(values, weights)) / total if total > 0 else None


def close(a, b, tol=TOL):
    return a is not None and b is not None and abs(float(a) - float(b)) <= tol


def reliability_weight(row, firm_index, cov, sigma2):
    firm = row.get("firm")
    if firm not in firm_index:
        return None
    i = firm_index[firm]
    return float(row["weight"]) / math.sqrt(1.0 + float(cov[i][i]) / sigma2)


def selected_question_groups(questions):
    """Reproduce the source builder's selected population/RCV cluster rule."""
    groups = defaultdict(list)
    for q in questions:
        ch = q.get("chamber")
        if ch == "House":
            if q.get("poll_scope") != "district":
                continue
            race = q.get("district", "")
            margin = num(q.get("scenario_axis_margin_pp"))
        elif ch == "Senate":
            race = q.get("race_id", "")
            party = (q.get("challenger_party") or "").upper()
            margin = num(q.get("two_party_margin_D_minus_R_pp")) if party == "D" else (
                num(q.get("two_party_margin_major_opposition_minus_R_pp")) if party == "I" else None)
        else:
            continue
        weight = num(q.get("combined_poll_weight"))
        qid, poll = q.get("question_id", ""), q.get("poll_id", "")
        if not race or not qid or not poll or margin is None or weight is None or weight <= 0:
            continue
        rank = int(num(q.get("combined_population_rank")) or 0)
        groups[(ch, race, poll)].append((q, margin, weight, rank))

    chosen = {}
    for key, rows in groups.items():
        top = max(x[3] for x in rows)
        selected = [x for x in rows if x[3] == top]
        if any(str(x[0].get("ranked_choice_final", "")).lower() in {"true", "1", "yes"} for x in selected):
            selected = [x for x in selected if str(x[0].get("ranked_choice_final", "")).lower() in {"true", "1", "yes"}]
        ids = sorted(x[0]["question_id"] for x in selected)
        chosen[key] = {
            "ids": ids,
            "margin": sum(x[1] for x in selected) / len(selected),
            "weight": sum(x[2] for x in selected) / len(selected),
            "rank": top,
            "pollsters": {x[0].get("pollster", "").strip() for x in selected if x[0].get("pollster", "").strip()},
            "questions": [x[0] for x in selected],
        }
    return chosen


def main():
    comps = read(A / "combined/current_components.csv")
    clusters = read(A / "current_inputs/current_poll_weight_clusters.csv")
    questions = read(A / "current_inputs/current_poll_questions.csv")
    normalized_house = read(A / "normalized/current_normalized_polls.csv")
    comparison = read(A / "corrected_current/poll_and_conditional_margin_comparison.csv")
    v2 = {(r.get("chamber"), r.get("current_unit")): r for r in comparison
          if r.get("case") == "firm" and r.get("cycle") == "2026" and r.get("horizon") == "1" and r.get("availability_lag") == "7"}

    # Recreate the exact current V2 House h=6 / lag=7 firm route and its
    # saved reliability adjustment; no fitting is done here.
    sys.path[:0] = [str(ROOT / "repair_dependencies/stacking"), str(A), str(P),
                    str(ROOT / "audit/individual_adoption_2026-10-26/engine"),
                    str(ROOT / "audit/individual_adoption_2026-10-26/combined")]
    import polling_adapter as pa
    pi, ev = pa.install_v2_inputs()
    read0 = pi.read

    def routed(path):
        if Path(path).resolve() == (P / "auxiliary/current_normalized_polls.csv").resolve():
            return read0(A / "normalized/current_normalized_polls.csv")
        return read0(path)

    pi.read = routed
    inputs = pi.Inputs()
    inputs.add_current()
    firm_config = next(c for c in ev.configs() if c.get("name") == "firm")
    v2_rows = inputs.standardized(2026, ISSUE_HORIZON, firm_config, RELEASE_LAG)
    ledger = next(x for x in json.loads((A / "corrected_current/fit_ledger.json").read_text(encoding="utf-8"))
                  if x.get("case") == "firm" and x.get("cycle") == 2026 and x.get("horizon") == ISSUE_HORIZON and x.get("availability_lag") == RELEASE_LAG)
    firm_index = {f: i + 2 for i, f in enumerate(ledger["correction_firms"])}
    cov = ledger["correction_covariance"]
    sigma2 = max(9.0, float(ledger["firm_model"]["sigma2"]))
    by_house_race = defaultdict(list)
    for q in v2_rows:
        if q.get("chamber") == "House":
            by_house_race[q.get("race", "")].append(q)

    expected_clusters = selected_question_groups(questions)
    saved_clusters = defaultdict(dict)
    for c in clusters:
        ch, race, poll = c.get("chamber"), c.get("race_id", ""), c.get("poll_id", "")
        if ch in {"House", "Senate"}:
            saved_clusters[(ch, race)][poll] = c
    question_by_id = defaultdict(list)
    for q in questions:
        if q.get("question_id"):
            question_by_id[q["question_id"]].append(q)
    norm_by_id = defaultdict(list)
    for q in normalized_house:
        if q.get("question_id"):
            norm_by_id[q["question_id"]].append(q)

    result, race_checks = [], []
    for r in comps:
        ch, race = r["chamber"], r["race"]
        polled = (num(r.get("surveys")) or 0) > 0
        expected_polls = num(r.get("poll_average_28day_cluster_count"))
        expected_firms = num(r.get("poll_average_28day_firm_count"))
        component_polls, component_firms = expected_polls, expected_firms
        comp_raw = num(r.get("raw_poll"))
        exact = False
        n_assumed = False
        complete_ids = True
        raw_source = None
        mean_n = mean_age = kish = None
        firms = set()
        wts = []
        count = matched_count = 0
        n_observed_count = n_fallback_count = 0
        details = {}

        if ch == "House":
            vr = by_house_race.get(race, [])
            target = v2.get(("House", race), {})
            ns, ages, margins = [], [], []
            expected_source_count = int(num(target.get("polls")) or 0)
            expected_source_firms = int(num(target.get("firms")) or 0)
            for q in vr:
                rw = reliability_weight(q, firm_index, cov, sigma2)
                if rw is None:
                    complete_ids = False
                    continue
                wts.append(rw)
                margins.append(float(q["margin"]))
                firms.add(q["firm"])
                n = num(q.get("n"))
                start, end = day(q.get("start")), day(q.get("date"))
                age = (CUTOFF - (start + (end - start) / 2)).days if start and end else None
                if n is not None:
                    ns.append((rw, n))
                if age is not None:
                    ages.append((rw, age))
                # Recover every selected question in this V2 cluster from the
                # normalized source, applying the same population and final
                # RCV selection. The engine's cluster stores only one qid.
                candidates = [x for x in normalized_house
                              if x.get("poll_id") == q.get("poll_id")
                              and x.get("district") == race
                              and str(x.get("scenario_axis_eligible", "")).lower() == "true"
                              and num(x.get("scenario_axis_margin_pp")) is not None]
                candidates = [x for x in candidates
                              if (end := day(x.get("end_date"))) is not None
                              and end <= CUTOFF
                              and (day(x.get("effective_model_availability_date")) or date.fromordinal(end.toordinal() + RELEASE_LAG)) <= CUTOFF
                              and (CUTOFF - ((day(x.get("start_date")) or end) + (end - (day(x.get("start_date")) or end)) / 2)).days <= 90]
                pop_rank = {"lv": 3, "rv": 2, "a": 1, "unknown": 0}.get(str(q.get("population", "unknown")).lower(), 0)
                same_rank = [x for x in candidates
                             if int(num(x.get("combined_population_rank")) or 0) == pop_rank]
                if any(str(x.get("ranked_choice_final", "")).lower() == "true" for x in same_rank):
                    same_rank = [x for x in same_rank if str(x.get("ranked_choice_final", "")).lower() == "true"]
                raw_n_values = [num(x.get("sample_size")) for x in same_rank]
                ids = {x.get("question_id", "") for x in same_rank}
                qcount = int(q.get("source_question_count", 1))
                if not same_rank or len(same_rank) != qcount or q.get("question_id") not in ids:
                    complete_ids = False
                n_observed_count += sum(x is not None for x in raw_n_values)
                n_fallback_count += sum(x is None for x in raw_n_values)
                if any(x is None for x in raw_n_values):
                    n_assumed = True
                # Inputs.clusters uses the selected-question mean, with 500
                # substituted for each missing N before averaging.
                cluster_n = sum(x if x is not None else 500 for x in raw_n_values) / len(raw_n_values) if raw_n_values else num(q.get("n"))
                if cluster_n is not None:
                    ns[-1] = (rw, cluster_n)
            count = len(vr)
            matched_count = sum(1 for q in vr if q.get("firm") in firm_index)
            mean_n = weighted_mean([x[1] for x in ns], [x[0] for x in ns]) if ns else None
            mean_age = weighted_mean([x[1] for x in ages], [x[0] for x in ages]) if ages else None
            raw_source = weighted_mean(margins, wts) if wts else None
            target_raw = num(target.get("raw_poll"))
            target_polls = num(target.get("polls"))
            target_firms = num(target.get("firms"))
            raw_match = close(raw_source, target_raw)
            source_match = (count == expected_source_count == int(target_polls or 0) == int(component_polls or 0)
                            and len(firms) == expected_source_firms == int(target_firms or 0) == int(component_firms or 0)
                            and close(comp_raw, target_raw)
                            and int(num(r.get("surveys")) or 0) == int(target_polls or 0))
            exact = bool(source_match and raw_match and complete_ids and count > 0)
            details = {"v2_polls": target_polls, "v2_firms": target_firms,
                       "v2_raw_poll": target_raw, "raw_poll_abs_error_vs_v2": abs(raw_source-target_raw) if raw_source is not None and target_raw is not None else None,
                       "source_count_match": source_match, "recomputed_raw_match": raw_match,
                       "selected_question_membership_complete": complete_ids,
                       "selected_question_N_observed": n_observed_count,
                       "selected_question_N_fallback": n_fallback_count}
            expected_polls, expected_firms = target_polls, target_firms
        elif ch == "Senate":
            # Source and saved cluster population must agree question by
            # question, including exact selected RCV round membership.
            key_race = race
            saved = saved_clusters.get(("Senate", key_race), {})
            expected = {poll: z for (cch, crace, poll), z in expected_clusters.items() if cch == "Senate" and crace == key_race}
            qids_complete = True
            source_firms = set()
            cluster_rows, cluster_weights, cluster_margins = [], [], []
            all_n, all_age = [], []
            for poll, z in expected.items():
                c = saved.get(poll)
                if c is None:
                    qids_complete = False
                    continue
                listed = sorted(x for x in c.get("source_question_ids", "").split(";") if x)
                if listed != z["ids"]:
                    qids_complete = False
                matched = [question_by_id.get(qid, []) for qid in z["ids"]]
                if any(len(x) != 1 for x in matched):
                    qids_complete = False
                    continue
                qs = [x[0] for x in matched]
                if not close(num(c.get("cluster_two_party_margin_pp")), z["margin"]) or not close(num(c.get("cluster_weight")), z["weight"]):
                    qids_complete = False
                saved_names = {x.strip().casefold() for x in c.get("pollster_names", "").split(";") if x.strip()}
                if saved_names != {x.strip().casefold() for x in z["pollsters"] if x.strip()}:
                    qids_complete = False
                qweights = [num(q.get("combined_poll_weight")) for q in qs]
                ns, ages = [], []
                for q, qw in zip(qs, qweights):
                    n = num(q.get("sample_size"))
                    midpoint = day(q.get("combined_field_midpoint"))
                    if n is None:
                        n_assumed = True
                        n = num(q.get("combined_weight_sample_size"))
                    if n is None or qw is None or qw <= 0 or midpoint is None:
                        qids_complete = False
                        continue
                    age = (CUTOFF - midpoint).days
                    ns.append((qw, n)); ages.append((qw, age))
                if len(ns) != len(qs):
                    qids_complete = False
                    continue
                cluster_n = weighted_mean([x[1] for x in ns], [x[0] for x in ns])
                cluster_age = weighted_mean([x[1] for x in ages], [x[0] for x in ages])
                cw = float(c["cluster_weight"])
                cluster_rows.append(c)
                cluster_weights.append(cw)
                cluster_margins.append(float(c["cluster_two_party_margin_pp"]))
                all_n.append((cw, cluster_n)); all_age.append((cw, cluster_age))
                source_firms.update(x.strip().casefold() for x in z["pollsters"] if x.strip())
                n_observed_count += sum(num(q.get("sample_size")) is not None for q in qs)
                n_fallback_count += sum(num(q.get("sample_size")) is None for q in qs)
            if set(saved) != set(expected):
                qids_complete = False
            firms = source_firms
            count = len(cluster_rows)
            matched_count = sum(len(x["ids"]) for x in expected.values()) if qids_complete else sum(len(question_by_id.get(qid, [])) == 1 for z in expected.values() for qid in z["ids"])
            mean_n = weighted_mean([x[1] for x in all_n], [x[0] for x in all_n]) if all_n else None
            mean_age = weighted_mean([x[1] for x in all_age], [x[0] for x in all_age]) if all_age else None
            total = sum(cluster_weights)
            raw_source = weighted_mean(cluster_margins, cluster_weights) if total > 0 else None
            kish = total * total / sum(w*w for w in cluster_weights) if cluster_weights and sum(w*w for w in cluster_weights) > 0 else 0.0
            source_match = (count == len(expected) == int(expected_polls or 0) == int(component_polls or 0)
                            and len(firms) == int(expected_firms or 0) == int(component_firms or 0)
                            and close(comp_raw, raw_source)
                            and int(num(r.get("surveys")) or 0) == count)
            exact = bool(source_match and qids_complete and count > 0)
            complete_ids = qids_complete
            details = {"selected_question_count": matched_count,
                       "selected_cluster_count": count,
                       "raw_poll_recomputed": raw_source,
                       "raw_poll_abs_error_vs_component": abs(raw_source-comp_raw) if raw_source is not None and comp_raw is not None else None,
                       "source_count_firm_match": source_match,
                       "selected_question_N_observed": n_observed_count,
                       "selected_question_N_fallback": n_fallback_count,
                       "all_source_question_ids_joined_and_selection_reproduced": qids_complete}
        else:
            exact = False

        if ch == "House" and polled:
            # Source route must reproduce the saved V2 point and current
            # component counts/center exactly; no self-derived parity fields.
            kish = (sum(wts)**2 / sum(w*w for w in wts)) if wts and sum(w*w for w in wts) else 0.0
        assumed = bool(n_assumed)
        status = "not_applicable" if not polled else ("verified" if exact else "unknown")
        precision = math.sqrt(min(2000, max(200, mean_n)) / 600) if mean_n is not None and not assumed else 1.0
        info = min(len(firms), kish or 0.0) * precision if status == "verified" else 0.0
        # mean_age is already measured from the source cutoff; do not subtract
        # the issue horizon a second time.
        fresh = 2 ** (-max(0.0, mean_age or 0.0) / 28) if status == "verified" else 1.0
        strength = max(-2.0, min(2.0, math.log2(info * fresh / 3))) if info > 0 else 0.0
        reason = ("unpolled_strength_not_applicable" if not polled else
                  "verified_exact_v2_h6_l7_reliability_and_component_parity" if ch == "House" and status == "verified" else
                  "verified_complete_selected_question_cluster_and_component_parity" if ch == "Senate" and status == "verified" else
                  "sample_size_missing_or_fallback" if assumed else "source_or_component_parity_incomplete")
        result.append({"cycle": 2026, "chamber": ch, "race": race, "polled": str(polled).lower(),
                       "strength_status": status, "strength_reason": reason,
                       "source_cluster_count": count, "matched_source_cluster_count": matched_count,
                       "distinct_firms": len(firms), "kish_effective_clusters": round(kish or 0.0, 8),
                       "weighted_mean_sample_size": round(mean_n, 8) if mean_n is not None else "",
                       "weighted_mean_age_days_at_2026_11_02": round(mean_age, 8) if mean_age is not None else "",
                       "issue_horizon_days": ISSUE_HORIZON, "release_availability_lag_days": RELEASE_LAG,
                       "sample_size_assumed": str(assumed).lower(), "source_v2_count_parity": str(bool(exact)).lower(),
                       "staged_v2_polls": expected_polls if expected_polls is not None else "",
                       "staged_v2_firms": expected_firms if expected_firms is not None else "",
                       "sample_size_precision_factor": round(precision, 8),
                       "information_index": round(info, 8), "freshness_factor": round(fresh, 8),
                       "verified_poll_strength": round(strength, 8)})
        race_checks.append({"chamber": ch, "race": race, "polled": polled, "status": status,
                            "count": count, "firms": len(firms), "sample_size_assumed": assumed,
                            "source_exact": exact, **details})

    fields = list(result[0])
    with OUT.open("w", encoding="utf-8", newline="") as f:
        w = csv.DictWriter(f, fieldnames=fields)
        w.writeheader(); w.writerows(result)
    counts = defaultdict(int)
    for r in result:
        counts[(r["chamber"], r["strength_status"])] += 1
    RECEIPT.parent.mkdir(exist_ok=True)
    hashes = {str(p.relative_to(ROOT)).replace("\\", "/"): hashlib.sha256(p.read_bytes()).hexdigest()
              for p in [OUT, Path(__file__), A / "combined/current_components.csv",
                        A / "current_inputs/current_poll_questions.csv", A / "current_inputs/current_poll_weight_clusters.csv",
                        A / "corrected_current/poll_and_conditional_margin_comparison.csv"]}
    RECEIPT.write_text(json.dumps({"status": "source_reconciliation_complete", "rows": len(result),
        "status_counts": {"|".join(k): v for k, v in sorted(counts.items())},
        "house_route": "current V2 firm; h=6; availability lag=7; saved covariance reliability; raw mean/counts/firms reconciled to V2 comparison and staged components",
        "senate_route": "authoritative current_poll_questions; source_question_ids fully joined; selected population/RCV cohort and cluster weighting independently reconstructed",
        "age_basis": "field midpoint age at 2026-11-02 source cutoff; issue horizon not subtracted again",
        "tolerance": TOL, "checks": race_checks, "input_output_sha256": hashes}, indent=2), encoding="utf-8")
    print(json.dumps({"rows": len(result), "status_counts": {"|".join(k): v for k, v in sorted(counts.items())},
                      "receipt": str(RECEIPT)}), flush=True)


if __name__ == "__main__":
    main()
