# -*- coding: utf-8 -*-
"""
asic_deals.py — transaction-based ASIC price curve for the Mining NAV Standard (v1.1).

Input : a deal panel (CSV in the normalized schema below, or an .xlsx/.csv in another layout mapped through
        a header-synonym table — e.g. the user's ASIC_purchase_prices_2024-2026_v3.xlsx).
Output: hedonic curve $/TH = f(J/TH) at the valuation date, fitted by weighted least squares on
        ln(P/TH) = a + b·(J/TH − 16) + g·months_before_T + d·secondary, with recency weights.
        The same regression is replicated in the workbook with LINEST (sheet ASIC_Curve), so Excel and
        Python results must agree to 1e-6 — this is part of the two-layer validation.

Method ("Методика цен для NAV-M", v1.1):
 1. Fit universe = PRIMARY-MARKET transactions only: rows with usd_per_th > 0 and jth > 0, price_fixing_date in
    (T − window_days, T], seller_type in {OEM_PRIMARY, SELLER_ASP} (new equipment bought from an OEM/distributor,
    or an OEM's reported average selling price), includes_non_miner not YES. Secondary / used-fleet sales
    (SECONDARY, BUYER_SALE), OEM trade-in credits (OEM_TRADEIN), related-party and MEMO rows stay in the panel
    for disclosure and for the secondary-discount statistic, but do not enter the curve.
 2. Specification: ln($/TH) = a + b·(J/TH − ref) + g·months_before_T, weighted least squares with recency weights
    w = exp(−ln2 · months_before_T / half_life); sqrt(w) applied to y and X so that a no-constant LINEST on the
    transformed columns gives the WLS solution (replicated in the workbook).
 3. Curve at T (months = 0): P_new(J) = exp(a + b·(J − ref)) — the primary-market price of equivalent new
    equipment of the fleet's efficiency class at the data cut (IPMK capital-base convention). g is the within-
    window price trend; time extrapolation from the latest in-sample deal to T is reported (months) and
    must not exceed max_extrap_months (else curve unavailable).
 4. Minimum sample: n ≥ min_n deals and ≥ min_distinct_jth distinct J/TH values; otherwise the curve is
    "unavailable" and NAV-M is not computed (no fallback to asking prices).
 5. Flags per company: J/TH outside [min J − tol_lo, max J + tol_hi] of the sample → "extrapolated";
    fewer than min_local deals within ± local_band J/TH of the fleet's J/TH → "sparse".
 6. Information: secondary discount = weighted mean of ln(P/curve) over secondary rows in the window.
"""
import csv, math, os, sys, json, datetime as dt

SCHEMA = ["deal_id", "buyer_ticker", "buyer_name", "seller", "seller_type", "announce_date", "price_fixing_date", "delivery_period",
          "model", "units", "th_per_unit", "total_th", "jth", "jth_basis", "total_usd", "usd_per_th", "price_basis", "payment_form",
          "includes_non_miner", "source_type", "source_url", "source_date", "quote", "notes", "confidence"]

FIT_SELLER_TYPES = {"OEM_PRIMARY", "SELLER_ASP"}
SECONDARY_TYPES = {"SECONDARY", "BUYER_SALE"}
DEFAULT_PARAMS = {"window_days": 730, "half_life_months": 9.0, "ref_jth": 16.0, "min_n": 8, "min_distinct_jth": 3, "extrap_lo": 1.0, "extrap_hi": 2.0, "max_extrap_months": 12.0, "local_band": 2.0, "min_local": 3}

# Header synonyms for mapping an external workbook (e.g. ASIC_purchase_prices v3) onto the schema. Lower-cased substring match.
SYNONYMS = {
    "deal_id": ["deal_id", "id сделки", "сделка id", "deal id", "№"],
    "buyer_ticker": ["buyer_ticker", "тикер покупателя", "ticker", "тикер"],
    "buyer_name": ["buyer_name", "покупатель", "buyer"],
    "seller": ["seller_name", "продавец", "seller"],
    "seller_type": ["seller_type", "тип продавца"],
    "announce_date": ["announce_date", "дата анонса", "дата объявления", "announced"],
    "price_fixing_date": ["price_fixing_date", "фиксац", "price fixing", "дата цены", "contract date", "дата сделки"],
    "delivery_period": ["delivery", "поставк"],
    "model": ["model", "модель"],
    "units": ["units", "количество", "кол-во", "штук", "qty"],
    "th_per_unit": ["th_per_unit", "th/unit", "th на", "хешрейт ед", "th per unit"],
    "total_th": ["total_th", "всего th", "total th", "th total", "общий хешрейт"],
    "jth": ["jth", "j/th", "дж/th", "эффективн", "efficiency"],
    "jth_basis": ["jth_basis"],
    "total_usd": ["total_usd", "сумма", "total usd", "total price", "стоимость сделки", "amount usd"],
    "usd_per_th": ["usd_per_th", "$/th", "usd/th", "цена за th", "price per th", "per th"],
    "price_basis": ["price_basis", "основание цены"],
    "payment_form": ["payment", "оплат"],
    "includes_non_miner": ["includes_non_miner", "включает"],
    "source_type": ["source_type", "тип источника"],
    "source_url": ["source_url", "url", "ссылка"],
    "source_date": ["source_date", "дата источника"],
    "quote": ["quote", "цитата"],
    "notes": ["notes", "примеч", "комментар"],
    "confidence": ["confidence", "надежн", "достоверн"],
}


def _num(x):
    if x is None: return None
    if isinstance(x, (int, float)): return float(x)
    s = str(x).strip().replace(",", "").replace("$", "").replace(" ", "")
    if s in ("", "ND", "n/a", "NA", "-", "—"): return None
    try: return float(s)
    except ValueError: return None


def _date(x):
    """Parse ISO dates; also '2025-Q1 …' (quarter end), 'FY2024 …' (year end), '2025-04 …' (15th of month). Free text after the token is ignored."""
    import re
    if x is None or x == "": return None
    if isinstance(x, dt.datetime): return x.date()
    if isinstance(x, dt.date): return x
    s = str(x).strip()
    m = re.match(r"(\d{4})-(\d{2})-(\d{2})", s)
    if m: return dt.date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
    m = re.match(r"(\d{4})-Q([1-4])", s) or (lambda mm: mm and type("M", (), {"group": lambda self, i: (mm.group(2), mm.group(1))[i - 1]})())(re.match(r"Q([1-4])\s?(\d{4})", s))
    if m:
        y, q = int(m.group(1)), int(m.group(2)); mo = 3 * q; return dt.date(y, mo, (31 if mo in (3, 12) else 30))
    m = re.match(r"(?:FY|CY)?\s?(\d{4})(?!-)", s)
    if m and (s.upper().startswith("FY") or s.upper().startswith("CY")): return dt.date(int(m.group(1)), 12, 31)
    m = re.match(r"(\d{4})-(\d{2})(?!\d)", s)
    if m: return dt.date(int(m.group(1)), int(m.group(2)), 15)
    m = re.match(r"(\d{2})\.(\d{2})\.(\d{4})", s)
    if m: return dt.date(int(m.group(3)), int(m.group(2)), int(m.group(1)))
    m = re.match(r"(\d{1,2})/(\d{1,2})/(\d{4})", s)
    if m: return dt.date(int(m.group(3)), int(m.group(1)), int(m.group(2)))
    return None


def read_normalized_csv(path):
    with open(path, encoding="utf-8-sig", newline="") as f:
        rows = list(csv.DictReader(f))
    return [{k: r.get(k, "") for k in SCHEMA} for r in rows]


def map_external(path, sheet=None, mapping=None):
    """Read an external xlsx/csv deal table and map headers onto SCHEMA using SYNONYMS (or an explicit mapping dict)."""
    if path.lower().endswith(".csv"):
        with open(path, encoding="utf-8-sig", newline="") as f:
            raw = list(csv.DictReader(f)); headers = list(raw[0].keys()) if raw else []
    else:
        import openpyxl
        wb = openpyxl.load_workbook(path, data_only=True, read_only=True)
        ws = wb[sheet] if sheet else _pick_deals_sheet(wb)
        data = list(ws.iter_rows(values_only=True))
        hi = _header_row(data); headers = [str(h).strip() if h is not None else "" for h in data[hi]]
        raw = [dict(zip(headers, row)) for row in data[hi + 1:] if any(v not in (None, "") for v in row)]
    mp = mapping or {}
    low = {h: h.lower() for h in headers}
    for key, syns in SYNONYMS.items():
        if key in mp: continue
        for h, hl in low.items():
            if any(s in hl for s in syns) and h not in mp.values():
                mp[key] = h; break
    out = []
    for r in raw:
        o = {k: (r.get(mp[k]) if k in mp else "") for k in SCHEMA}
        for k in ("announce_date", "price_fixing_date", "source_date"):
            d = _date(o[k]); o[k] = d.isoformat() if d else ""
        for k in ("units", "th_per_unit", "total_th", "jth", "total_usd", "usd_per_th"):
            v = _num(o[k]); o[k] = "" if v is None else v
        if o["usd_per_th"] == "" and o["total_usd"] != "" and o["total_th"] not in ("", 0): o["usd_per_th"] = o["total_usd"] / o["total_th"]; o["price_basis"] = o["price_basis"] or "DERIVED_TOTAL_DIV_TH"
        if o["total_th"] == "" and o["units"] != "" and o["th_per_unit"] != "": o["total_th"] = o["units"] * o["th_per_unit"]
        o["seller_type"] = (str(o["seller_type"]).strip().upper() or "OEM_PRIMARY") if o["seller_type"] not in (None, "") else "OEM_PRIMARY"
        out.append(o)
    return out, mp


def _pick_deals_sheet(wb):
    best, score = None, -1
    for ws in wb.worksheets:
        head = [str(c).lower() for row in ws.iter_rows(min_row=1, max_row=6, values_only=True) for c in row if c is not None]
        s = sum(any(k in h for h in head) for k in ("th", "j/th", "$/th", "модель", "model", "покупатель", "buyer"))
        if s > score: best, score = ws, s
    return best


def _header_row(data):
    for i, row in enumerate(data[:10]):
        vals = [str(v).lower() for v in row if v is not None]
        if sum(any(k in v for k in ("th", "model", "модель", "buyer", "покупатель", "date", "дата")) for v in vals) >= 2: return i
    return 0


def fit_rows(deals, T, P=None):
    """Return (sample rows with derived columns, excluded rows with reason)."""
    P = dict(DEFAULT_PARAMS, **(P or {}))
    T = _date(T) if not isinstance(T, dt.date) else T
    lo = T - dt.timedelta(days=P["window_days"])
    sample, excluded = [], []
    for r in deals:
        price = _num(r.get("usd_per_th")); j = _num(r.get("jth")); d = _date(r.get("price_fixing_date") or r.get("announce_date"))
        st = str(r.get("seller_type", "")).strip().upper(); inc = str(r.get("includes_non_miner", "")).strip().upper()
        why = None
        if price is None or price <= 0: why = "no price"
        elif j is None or j <= 0: why = "no J/TH"
        elif d is None: why = "no date"
        elif not (lo < d <= T): why = "outside window"
        elif inc == "YES": why = "price includes non-miner items"
        elif st not in FIT_SELLER_TYPES and st not in SECONDARY_TYPES: why = f"seller_type {st or 'blank'} not in fit set"
        months = (T - d).days / 30.4375 if d else None
        w = math.exp(-math.log(2) * months / P["half_life_months"]) if months is not None else 0.0
        row = dict(r, _price=price, _j=j, _date=d, _months=months, _sec=(1.0 if st in SECONDARY_TYPES else 0.0), _w=w, _sw=math.sqrt(w), _y=(math.log(price) if price and price > 0 else None))
        if why: excluded.append((r, why)); continue
        if st in SECONDARY_TYPES: excluded.append((row, "secondary (information only)")); continue
        sample.append(row)
    return sample, excluded, P


def wls(sample, P):
    """Solve WLS for ln P = a + b(J-16) + g*months + d*sec. Returns dict or None if insufficient."""
    n = len(sample); distinct = len({round(s["_j"], 2) for s in sample})
    if n < P["min_n"] or distinct < P["min_distinct_jth"]: return None
    extrap_months = min(s["_months"] for s in sample)
    if extrap_months > P["max_extrap_months"]: return None
    cols = [lambda s: 1.0, lambda s: s["_j"] - P["ref_jth"], lambda s: s["_months"]]
    k = len(cols)
    XtX = [[0.0] * k for _ in range(k)]; Xty = [0.0] * k
    for s in sample:
        x = [c(s) * s["_sw"] for c in cols]; y = s["_y"] * s["_sw"]
        for i in range(k):
            Xty[i] += x[i] * y
            for jx in range(k): XtX[i][jx] += x[i] * x[jx]
    beta = _solve(XtX, Xty)
    if beta is None: return None
    # weighted R² and residual SE
    ybar = sum(s["_y"] * s["_w"] for s in sample) / sum(s["_w"] for s in sample)
    sse = sst = 0.0
    for s in sample:
        x = [c(s) for c in cols]; yhat = sum(b * xi for b, xi in zip(beta, x))
        sse += s["_w"] * (s["_y"] - yhat) ** 2; sst += s["_w"] * (s["_y"] - ybar) ** 2
    r2 = 1 - sse / sst if sst > 0 else None
    se = math.sqrt(sse / max(1, n - k))
    eff_age = sum(s["_w"] * s["_months"] for s in sample) / sum(s["_w"] for s in sample)
    return dict(n=n, k=k, a=beta[0], b=beta[1], g=beta[2], r2=r2, se=se,
                jmin=min(s["_j"] for s in sample), jmax=max(s["_j"] for s in sample), distinct_jth=distinct,
                monthly_drift=math.exp(beta[2]) - 1, ref_price=math.exp(beta[0]), extrap_months=extrap_months, eff_age_months=eff_age,
                latest_deal=max(s["_date"] for s in sample).isoformat())


def secondary_discount(fit, excluded, P=None):
    """Weighted mean of ln(P/curve) over secondary rows inside the window (information only)."""
    P = dict(DEFAULT_PARAMS, **(P or {}))
    rows = [r for r, why in excluded if why == "secondary (information only)"]
    if not fit or not rows: return None, len(rows)
    num = sum(r["_w"] * (r["_y"] - (fit["a"] + fit["b"] * (r["_j"] - P["ref_jth"]) + fit["g"] * r["_months"])) for r in rows)
    den = sum(r["_w"] for r in rows)
    return (num / den if den else None), len(rows)


def local_count(sample, jth, P=None):
    P = dict(DEFAULT_PARAMS, **(P or {}))
    return sum(1 for s in sample if abs(s["_j"] - jth) <= P["local_band"])


def _solve(A, b):
    n = len(b); M = [row[:] + [b[i]] for i, row in enumerate(A)]
    for i in range(n):
        p = max(range(i, n), key=lambda r: abs(M[r][i]))
        if abs(M[p][i]) < 1e-12: return None
        M[i], M[p] = M[p], M[i]
        for r in range(n):
            if r != i:
                f = M[r][i] / M[i][i]
                for c in range(i, n + 1): M[r][c] -= f * M[i][c]
    return [M[i][n] / M[i][i] for i in range(n)]


def price_at(fit, jth, P=None):
    P = dict(DEFAULT_PARAMS, **(P or {}))
    return math.exp(fit["a"] + fit["b"] * (jth - P["ref_jth"]))


def extrapolated(fit, jth, P=None):
    P = dict(DEFAULT_PARAMS, **(P or {}))
    return jth < fit["jmin"] - P["extrap_lo"] or jth > fit["jmax"] + P["extrap_hi"]


def bucket_medians(sample, edges=(0, 14, 16, 18.5, 22, 30, 99)):
    out = []
    for lo, hi in zip(edges[:-1], edges[1:]):
        v = sorted(s["_price"] for s in sample if lo <= s["_j"] < hi)
        if v: out.append((f"[{lo},{hi})", len(v), v[len(v) // 2] if len(v) % 2 else (v[len(v) // 2 - 1] + v[len(v) // 2]) / 2))
    return out


def load_panel(path, sheet=None, mapping=None):
    if path.lower().endswith(".csv"):
        with open(path, encoding="utf-8-sig", newline="") as f:
            hdr = next(csv.reader(f))
        if set(SCHEMA[:6]).issubset(set(h.strip() for h in hdr)): return read_normalized_csv(path), {}
    return map_external(path, sheet, mapping)


def write_normalized(rows, path):
    with open(path, "w", encoding="utf-8", newline="") as f:
        w = csv.DictWriter(f, fieldnames=SCHEMA); w.writeheader()
        for r in rows: w.writerow({k: r.get(k, "") for k in SCHEMA})


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser(); ap.add_argument("panel"); ap.add_argument("--date", default="2026-10-15"); ap.add_argument("--sheet"); ap.add_argument("--json")
    a = ap.parse_args()
    rows, mp = load_panel(a.panel, a.sheet)
    sample, excl, P = fit_rows(rows, a.date)
    fit = wls(sample, P)
    print(f"panel rows {len(rows)}; in fit sample {len(sample)}; excluded {len(excl)}; mapping {mp if mp else 'normalized'}")
    if fit:
        sd, ns = secondary_discount(fit, excl, P)
        print(f"fit n={fit['n']} k={fit['k']} a={fit['a']:.4f} (ref {fit['ref_price']:.2f} $/TH @16 J/TH) b={fit['b']:.4f} g={fit['g']:.4f} ({fit['monthly_drift']*100:+.2f}%/mo back) R2={fit['r2']:.3f} se={fit['se']:.3f} J range {fit['jmin']}-{fit['jmax']} latest {fit['latest_deal']} extrap {fit['extrap_months']:.1f} mo eff_age {fit['eff_age_months']:.1f} mo; secondary discount {sd} over {ns} rows")
        for j in (12, 13.5, 15, 16, 17.5, 19, 21.5, 25, 29.5): print(f"  {j:5.1f} J/TH -> {price_at(fit, j):6.2f} $/TH{'  (extrap)' if extrapolated(fit, j) else ''}")
        for b in bucket_medians(sample): print("  bucket", b)
    else: print("curve unavailable (insufficient sample)")
    if a.json: json.dump(dict(fit=fit, params=P, n_rows=len(rows)), open(a.json, "w"), indent=2, default=str)
