#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Baseline logistic model for the synthetic MMB dataset.

Uses only observable monthly metrics. Excludes all ground-truth labels
(months_to_default, is_defaulted_firm, default_next_12m).

Run:
    /opt/data/workspace/.venv/bin/python baseline_model.py
"""
import json
import math
import numpy as np
import pandas as pd

SIM = "/opt/data/workspace/data/sim"
FEATURES = [
    "log_revenue",
    "fixed_expense_ratio",
    "runway_days",
    "receipts_yoy_pct",
    "overdraft_utilization",
    "dso_days",
    "current_ratio",
    "quick_ratio",
    "dscr",
    "interest_coverage",
    "debt_ebitda",
    "equity_ratio",
    "late_share",
    "avg_days_late",
    "top1_share",
    "hhi",
    "client_count",
    "net_margin_pct",
    "ocf_to_net_income",
]


def auc(y, s):
    y = np.asarray(y, dtype=int)
    s = np.asarray(s, dtype=float)
    order = np.argsort(s, kind="mergesort")
    ranked = np.empty(len(s), dtype=float)
    ranked[order] = np.arange(1, len(s) + 1, dtype=float)
    # tie correction
    _, inv, cnt = np.unique(s, return_inverse=True, return_counts=True)
    out = np.empty(len(s), dtype=float)
    start = 0
    for i in range(len(cnt)):
        idx = np.where(inv == i)[0]
        out[idx] = (start + 1 + start + len(idx)) / 2.0
        start += len(idx)
    n1 = int(y.sum())
    n0 = len(y) - n1
    if not n1 or not n0:
        return float("nan")
    return float((out[y == 1].sum() - n1 * (n1 + 1) / 2) / (n1 * n0))


def ks(y, s):
    y = np.asarray(y, dtype=int)
    s = np.asarray(s, dtype=float)
    order = np.argsort(-s)
    y = y[order]
    cum = np.cumsum(y)
    n1 = len(y) if y.sum() == 0 else y.sum()
    n0 = len(y) - n1
    if n1 == 0 or n0 == 0:
        return float("nan")
    tpr = cum / n1
    fpr = (np.arange(1, len(y) + 1) - cum) / n0
    return float(np.max(tpr - fpr))


def main():
    df = pd.read_csv(f"{SIM}/monthly_metrics.csv")
    df["log_revenue"] = np.log1p(df["revenue"].clip(lower=0))
    y = df["default_next_12m"].astype(int).values

    tr = df[df["split"] == "train"].reset_index(drop=True)
    te = df[df["split"] == "test"].reset_index(drop=True)
    Xtr = tr[FEATURES].astype(float).to_numpy()
    ytr = tr["default_next_12m"].astype(int).to_numpy()
    Xte = te[FEATURES].astype(float).to_numpy()
    yte = te["default_next_12m"].astype(int).to_numpy()

    med = np.nanmedian(Xtr, axis=0)
    med = np.where(np.isfinite(med), med, 0.0)
    Xtr = np.where(np.isfinite(Xtr), Xtr, med)
    Xte = np.where(np.isfinite(Xte), Xte, med)

    mu = Xtr.mean(axis=0)
    sd = Xtr.std(axis=0)
    sd[sd < 1e-8] = 1.0
    Xtr = (Xtr - mu) / sd
    Xte = (Xte - mu) / sd

    # logistic regression with L2, full-batch gradient descent
    n, d = Xtr.shape
    w = np.zeros(d)
    b = 0.0
    lr = 0.35
    l2 = 1e-4
    for it in range(450):
        z = Xtr @ w + b
        p = 1.0 / (1.0 + np.exp(-np.clip(z, -30, 30)))
        g = p - ytr
        gw = (Xtr.T @ g) / n + l2 * w
        gb = g.mean()
        w -= lr * gw
        b -= lr * gb
        if it % 100 == 0:
            print(f"iter {it}: loss={-np.mean(ytr*np.log(p+1e-12)+(1-ytr)*np.log(1-p+1e-12)):.4f}")

    pte = 1.0 / (1.0 + np.exp(-np.clip(Xte @ w + b, -30, 30)))
    ptr = 1.0 / (1.0 + np.exp(-np.clip(Xtr @ w + b, -30, 30)))

    res = {
        "train_rows": int(len(ytr)),
        "test_rows": int(len(yte)),
        "train_pos": int(ytr.sum()),
        "test_pos": int(yte.sum()),
        "train_prevalence": float(ytr.mean()),
        "test_prevalence": float(yte.mean()),
        "train_auc": auc(ytr, ptr),
        "test_auc": auc(yte, pte),
        "test_ks": ks(yte, pte),
        "test_ks_pct": pte.mean(),
    }
    # top-decile precision
    k = max(1, int(len(pte) * 0.10))
    idx = np.argsort(-pte)[:k]
    res["top10_precision"] = float(yte[idx].mean())
    res["top10_recall"] = float(yte[idx].sum() / yte.sum())

    res["coefficients"] = {f: round(float(c), 4) for f, c in zip(FEATURES, w)}
    print(json.dumps(res, indent=2, ensure_ascii=False))
    with open(f"{SIM}/model_metrics.json", "w", encoding="utf-8") as fh:
        json.dump(res, fh, indent=2, ensure_ascii=False)
    with open(f"{SIM}/model_metrics.txt", "w", encoding="utf-8") as fh:
        fh.write(f"train_rows={res['train_rows']} test_rows={res['test_rows']}\n")
        fh.write(f"train_auc={res['train_auc']:.4f} test_auc={res['test_auc']:.4f} ks={res['test_ks']:.4f}\n")
        fh.write(f"top10_precision={res['top10_precision']:.4f} top10_recall={res['top10_recall']:.4f}\n")


if __name__ == "__main__":
    main()
