"""One contract traced through the price waterfall (price-waterfall.html, "One contract, traced"). Decided after the
results: an independent review asked for a worked example, so this file and results-pricing-trace.json were added after
results-pricing.json was written. It changes no check, control, prediction or figure of the declared run.

Usage: python -B site/trace_pricing.py <clean warehouse.duckdb> [results-pricing-trace.json]
The warehouse is the pricing round's clean database (make pricing leaves it at
runtime/pricing-run/db/clean/warehouse.duckdb). It sits outside pricing/ so that the round's code hash stays unchanged.

The contract is chosen by a stated rule: the first contract by contract id that is in service on
every day of the measured year, carries a discount above zero and an onboarding fee above zero, has a tier starting inside the year whose list
value is above the tier before it (a ramp step), and has no credit issued in the year. Its walk uses the same models and the same
formulas as fct_price_to_revenue, restricted to that one contract; its month-end prices come from int_line_month_end;
the ramp step is split with fct_retention_price_volume's rule (list effect = change in list ARR times the old realized
over list; discount effect = the rest). The contract's terms are also read from the generator's own records and must
agree. The ramp step's start day is read from the contract's tiers, and the year's list value must equal its days at each
list price. The same queries, run over every contract, must give the sales-led lines of results-pricing.json's walk to
the cent once the year's credits are taken off (the walk takes credits off before realized value; the traced contract has
none). The last line is the verdict.
"""
from __future__ import annotations

import json
import sys
from datetime import date
from decimal import Decimal
from pathlib import Path

import duckdb

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from warehouse import generate as g  # noqa: E402

YEAR_START, YEAR_END, START_MONTH, END_MONTH, YEAR_DAYS = "2025-10-01", "2026-09-30", "2025-09-01", "2026-09-01", 365
TOL = 0.01


def rows(con, sql: str, params: list | None = None) -> list[dict]:
    cur = con.execute(sql, params or [])
    names = [d[0] for d in cur.description]
    return [dict(zip(names, r)) for r in cur.fetchall()]


def num(v) -> float:
    return float(v) if isinstance(v, Decimal) else v


def pick(con) -> str:
    found = rows(con, f"""
        select c.contract_id
        from staging.stg_crm_contracts as c
        where c.service_start < date '{YEAR_START}' and c.service_end >= date '{YEAR_END}'
          and c.discount_pct > 0 and c.onboarding_fee > 0
          and exists (select 1 from staging.stg_crm_contract_tiers as t
                      inner join staging.stg_crm_contract_tiers as u on u.contract_id = t.contract_id and u.tier = t.tier - 1
                      where t.contract_id = c.contract_id and t.annual_list_value > u.annual_list_value
                        and t.tier_start > date '{YEAR_START}' and t.tier_start <= date '{YEAR_END}')
          and not exists (select 1 from staging.stg_contract_credits as k where k.contract_id = c.contract_id
                          and k.issued_on between date '{YEAR_START}' and date '{YEAR_END}')
        order by c.contract_id limit 1""")
    if not found:
        raise SystemExit("no contract meets the rule; nothing to trace")
    return found[0]["contract_id"]


def contract_walk(con, cid: str | None) -> tuple[dict, bool]:
    """The walk's lines for one contract, or for every contract when cid is None (same queries, no filter)."""
    one = cid is not None
    p = [cid] if one else []
    f_line = "and line_id = ?" if one else ""
    f_contract = "and contract_id = ?" if one else ""
    f_price = "where line_id = ?" if one else "where line_id in (select contract_id from staging.stg_crm_contracts)"
    priced = rows(con, f"""select sum(list_arr) / {YEAR_DAYS} as list_value, sum(discount_arr) / {YEAR_DAYS} as discount
                           from realization.int_price_daily {f_price}""", p)[0]
    realized = rows(con, f"""select sum(arr) / {YEAR_DAYS} as realized_value from intermediate.int_arr_daily
                             where line_kind = 'contract' {f_line}
                               and day between date '{YEAR_START}' and date '{YEAR_END}'""", p)[0]
    monthly = rows(con, f"""select sum(arr_day_sum / (12.0 * days_in_month)) as arr_by_month,
                                   sum(recognised - arr_day_sum / (12.0 * days_in_month)) as month_length
                            from intermediate.int_arr_line_monthly
                            where line_kind = 'contract' {f_line}
                              and month_start between date '{YEAR_START}' and date '{END_MONTH}'""", p)[0]
    policy = rows(con, f"""select sum(recognised_recurring) as policy_recurring, sum(recognised_one_off) as onboarding_fees
                           from intermediate.int_contract_revenue
                           where month_start between date '{YEAR_START}' and date '{END_MONTH}' {f_contract}""", p)[0]
    period = rows(con, f"""select sum(recognised_recurring) as period_recurring from intermediate.int_contract_recognition
                           where month_start between date '{YEAR_START}' and date '{END_MONTH}' {f_contract}""", p)[0]
    lv, disc, rv = num(priced["list_value"]), num(priced["discount"]), num(realized["realized_value"])
    dw = num(monthly["arr_by_month"]) - rv
    ml = num(monthly["month_length"])
    sl = num(policy["policy_recurring"]) - num(period["period_recurring"])
    fees = num(policy["onboarding_fees"])
    rec = num(policy["policy_recurring"]) + fees
    walk = {"list_value": round(lv, 2), "discount": round(disc, 2), "realized_value": round(rv, 2),
            "day_weighting": round(dw, 2), "month_length": round(ml, 2), "straight_lining": round(sl, 2),
            "onboarding_fees": round(fees, 2), "recognised_revenue": round(rec, 2),
            "billed_period_recurring": round(num(period["period_recurring"]), 2)}
    closes = abs(rv + dw + ml + sl + fees - rec) <= TOL and abs(lv - disc - rv) <= TOL
    return walk, closes


def trace(db: Path) -> dict:
    con = duckdb.connect(str(db), read_only=True)
    cid = pick(con)
    p = [cid]
    terms = rows(con, """select c.contract_id, a.segment, c.term_months, c.discount_pct, c.billing_frequency,
                                c.onboarding_fee, c.service_start, c.service_end
                         from staging.stg_crm_contracts as c
                         inner join staging.stg_crm_accounts as a on a.account_id = c.account_id
                         where c.contract_id = ?""", p)[0]
    tiers = rows(con, "select tier, tier_start, tier_end, annual_list_value from staging.stg_crm_contract_tiers "
                      "where contract_id = ? order by tier", p)
    walk, closes = contract_walk(con, cid)
    months = rows(con, f"""select month_start, list_arr, discount_pct, realized_arr from pricing.int_line_month_end
                           where line_id = ? and month_start between date '{START_MONTH}' and date '{END_MONTH}'
                           order by month_start""", p)
    every, _ = contract_walk(con, None)
    credits = num(rows(con, f"""select sum(amount) as credits from staging.stg_contract_credits
                                where issued_on between date '{YEAR_START}' and date '{YEAR_END}'""")[0]["credits"])
    n_contracts = rows(con, "select count(*) as n from staging.stg_crm_contracts")[0]["n"]
    con.close()

    series = [{"month": i, "list_arr": num(m["list_arr"]), "discount_pct": num(m["discount_pct"]),
               "realized_arr": num(m["realized_arr"])} for i, m in enumerate(months)]   # month 0 is the starting point
    steps = []
    in_year = [t for t in tiers if YEAR_START < str(t["tier_start"]) <= YEAR_END]
    for a, b in zip(series, series[1:]):
        if b["list_arr"] != a["list_arr"]:
            list_effect = (b["list_arr"] - a["list_arr"]) * a["realized_arr"] / a["list_arr"]
            steps.append({"month": b["month"], "list_before": a["list_arr"], "list_after": b["list_arr"],
                          "realized_before": a["realized_arr"], "realized_after": b["realized_arr"],
                          "list_effect": round(list_effect, 2),
                          "discount_effect": round(b["realized_arr"] - a["realized_arr"] - list_effect, 2)})
    # where the step falls inside its month, and the year's list value as days at each price
    step_day = in_year[0]["tier_start"].day if len(in_year) == 1 else None
    first = in_year[0]["tier_start"] if in_year else None
    days_before = (first - date.fromisoformat(YEAR_START)).days if first else None
    days_list = ((days_before * num(tiers[0]["annual_list_value"]) + (YEAR_DAYS - days_before) * num(tiers[1]["annual_list_value"]))
                 / YEAR_DAYS) if first and len(tiers) == 2 else None
    whole_months = ((steps[0]["month"] - 1) * num(tiers[0]["annual_list_value"])
                    + (12 - steps[0]["month"] + 1) * num(tiers[1]["annual_list_value"])) / 12 if steps and len(tiers) == 2 else None
    if steps:
        steps[0].update({"start_day_of_month": step_day, "days_at_first_list": days_before,
                         "days_at_second_list": YEAR_DAYS - days_before,
                         "list_value_by_whole_months": round(whole_months, 2)})

    # the same queries over every contract against the sales-led walk in results-pricing.json
    sl_walk = json.loads((ROOT / "results-pricing.json").read_text(encoding="utf-8"))["analysis"]["sales_led_walk"]
    pairs = {"list_value": (every["list_value"], sl_walk["list_value"]),
             "discount": (every["discount"], sl_walk["contract_discount"] + sl_walk["migration_discount"]),
             "realized_value": (every["realized_value"] - credits, sl_walk["realized_value"]),
             "day_weighting": (every["day_weighting"], sl_walk["day_weighting"]),
             "month_length": (every["month_length"], sl_walk["month_length"]),
             "straight_lining": (every["straight_lining"], sl_walk["straight_lining"]),
             "onboarding_fees": (every["onboarding_fees"], sl_walk["onboarding_fees"]),
             "recognised_revenue": (every["recognised_revenue"] - credits, sl_walk["recognised_revenue"])}
    every_contract = {"contracts": n_contracts, "credits_in_year": round(credits, 2),
                      "largest_difference": round(max(abs(a - b) for a, b in pairs.values()), 2)}

    co = g.Company(g.SEED).run()
    gc = next(c for c in co.contracts if c["contract_id"] == cid)
    gen = {"discount_pct": gc["discount_pct"] == terms["discount_pct"],
           "onboarding_fee": Decimal(gc["onboarding_fee"] or 0) == Decimal(terms["onboarding_fee"]),
           "service": (gc["service_start"], gc["service_end"]) == (terms["service_start"], terms["service_end"]),
           "tiers": [Decimal(t["annual_list_value"]) for t in gc["tiers"]] == [Decimal(t["annual_list_value"]) for t in tiers]}
    return {
        "decided_after_results": True,
        "why": "worked example asked for by an independent review after results-pricing.json was written",
        "rule": "lowest contract id in service every day of the measured year, discount above 0, onboarding fee above 0, "
                "a tier starting inside the year above the tier before it, no credit in the year",
        "contract": {"contract_id": cid, "segment": terms["segment"], "term_months": terms["term_months"],
                     "discount_pct": num(terms["discount_pct"]), "billing_frequency": terms["billing_frequency"],
                     "onboarding_fee": num(terms["onboarding_fee"]),
                     "tiers": [{"tier": t["tier"], "annual_list_value": num(t["annual_list_value"])} for t in tiers]},
        "walk": walk,
        "months": series,
        "ramp_steps": steps,
        "every_contract": every_contract,
        "checks": {"walk_closes": closes, "one_ramp_step_in_year": len(steps) == 1,
                   "step_month_matches_tier_start": bool(steps) and len(in_year) == 1
                   and (first.year - int(START_MONTH[:4])) * 12 + first.month - int(START_MONTH[5:7]) == steps[0]["month"],
                   "list_value_is_days_at_each_price": days_list is not None and abs(days_list - walk["list_value"]) <= TOL,
                   "every_contract_matches_sales_led_walk": every_contract["largest_difference"] <= TOL,
                   "step_discount_effect_zero": all(abs(s["discount_effect"]) <= TOL for s in steps),
                   "terms_match_generator": all(gen.values())},
    }


def main(argv: list[str]) -> int:
    db = Path(argv[0])
    out = Path(argv[1]) if len(argv) > 1 else ROOT / "results-pricing-trace.json"
    t = trace(db)
    out.write_text(json.dumps(t, indent=1, sort_keys=False) + "\n", encoding="utf-8")
    ok = all(t["checks"].values())
    print(f"VERDICT: {'PASS' if ok else 'FAIL'} (contract {t['contract']['contract_id']}; checks {t['checks']})")
    return 0 if ok else 1


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
