#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Dashboard server for the synthetic MMB portfolio.

As-of date: 2025-12-31. Only observable 2024-2025 metrics are used;
the 2026 default label is used for offline validation and never exposed
to the UI.

Serves static files from ./static and JSON from /api.
"""
import json
import os
import re
import socketserver
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import unquote

import pandas as pd

ROOT = os.path.dirname(os.path.abspath(__file__))
DATA = "/opt/data/workspace/data/sim"
AS_OF = "2025-12"
AS_OF_MONTH_INDEX = 23

ZONES = [
    (60, "Критический", "critical"),
    (45, "Высокий", "high"),
    (30, "Повышенный", "elevated"),
    (18, "Наблюдение", "watch"),
    (0, "Устойчивый", "stable"),
]


def num(v, default=0.0):
    try:
        if v is None or (isinstance(v, float) and pd.isna(v)):
            return default
        if isinstance(v, str) and v.strip() in ("", "nan"):
            return default
        return float(v)
    except Exception:
        return default


def risk_score(r):
    yoy = num(r.get("receipts_yoy_pct"), 0.0)
    hard = num(r.get("fixed_expense_ratio"), 0.0)
    run = num(r.get("runway_days"), 0.0)
    dso = num(r.get("dso_days"), 0.0)
    cur = num(r.get("current_ratio"), 2.0)
    ovr = num(r.get("overdraft_utilization"), 0.0)
    late = num(r.get("late_share"), 0.0)
    top1 = num(r.get("top1_share"), 0.0)
    eq = num(r.get("equity_ratio"), 0.5)
    dscr = num(r.get("dscr"), 3.0)

    s = 0.0
    s += min(22.0, max(0.0, -yoy / 3.0 * 1.6))
    s += min(15.0, max(0.0, (hard - 0.40) / 0.12 * 15.0))
    s += min(15.0, max(0.0, (12.0 - run) / 12.0 * 15.0))
    s += min(10.0, max(0.0, (dso - 45.0) / 35.0 * 10.0))
    s += min(8.0, max(0.0, (1.3 - cur) / 1.3 * 8.0))
    s += min(10.0, ovr * 14.0)
    s += min(10.0, late / 0.06 * 10.0)
    s += min(8.0, max(0.0, (top1 - 0.30) / 0.45 * 8.0))
    s += min(6.0, max(0.0, (0.30 - eq) / 0.5 * 6.0))
    s += min(6.0, max(0.0, (1.2 - dscr) / 1.2 * 6.0))
    return round(min(100.0, s), 1)


def zone_of(score):
    for threshold, label, code in ZONES:
        if score >= threshold:
            return label, code
    return "Устойчивый", "stable"


def fmt_money(x):
    x = float(x)
    if abs(x) >= 1_000_000:
        return f"{x/1_000_000:.1f} млн ₽"
    if abs(x) >= 1_000:
        return f"{x/1_000:.0f} тыс ₽"
    return f"{x:.0f} ₽"


def pct(v):
    return f"{float(v):+.1f}%"


def build_signals(r):
    out = []
    yoy = num(r.get("receipts_yoy_pct"), 0)
    par = num(r.get("fixed_expense_ratio"), 0)
    run = num(r.get("runway_days"), 0)
    dso = num(r.get("dso_days"), 0)
    ovr = num(r.get("overdraft_utilization"), 0)
    late = num(r.get("late_share"), 0)
    top1 = num(r.get("top1_share"), 0)
    cur = num(r.get("current_ratio"), 1)
    eq = num(r.get("equity_ratio"), 1)
    if yoy <= -12:
        out.append((4, "Выручка", f"{yoy:+.1f}% г/г"))
    elif yoy <= -4:
        out.append((2, "Выручка", f"{yoy:+.1f}% г/г"))
    if par >= 0.55:
        out.append((4, "Постоянные расходы", f"{par*100:.0f}% поступлений"))
    elif par >= 0.35:
        out.append((2, "Постоянные расходы", f"{par*100:.0f}% поступлений"))
    if run < 20:
        out.append((4, "Запас денег", f"{run:.0f} дней"))
    elif run < 45:
        out.append((2, "Запас денег", f"{run:.0f} дней"))
    if ovr >= 0.35:
        out.append((3, "Овердрафт", f"{ovr*100:.0f}% лимита"))
    elif ovr > 0.02:
        out.append((1, "Овердрафт", f"{ovr*100:.0f}% лимита"))
    if late >= 0.04:
        out.append((3, "Просрочки", f"{late*100:.0f}% платежей"))
    if dso >= 55:
        out.append((3, "Дебиторка", f"{dso:.0f} дней"))
    elif dso >= 40:
        out.append((1, "Дебиторка", f"{dso:.0f} дней"))
    if top1 >= 0.40:
        out.append((2, "Концентрация", f"топ-1 {top1*100:.0f}%"))
    if cur < 1.0:
        out.append((3, "Ликвидность", f"current {cur:.2f}"))
    if eq < 0.20:
        out.append((2, "Капитал", f"{eq*100:.0f}% активов"))
    out.sort(key=lambda x: -x[0])
    return [{"severity": s, "label": t, "value": v} for s, t, v in out[:6]]


def compact_row(fid, r):
    return {
        "id": fid,
        "name": "",
        "industry": r["industry"],
        "region": r["region"],
        "segment": r["segment"],
        "revenue": num(r["revenue"]),
        "yoy": num(r["receipts_yoy_pct"]) if pd.notna(r["receipts_yoy_pct"]) else None,
        "score": 0.0,
        "zone": "",
        "zone_code": "",
        "runway": num(r["runway_days"]),
        "fixed": num(r["fixed_expense_ratio"]),
        "dso": num(r["dso_days"]),
        "overdraft": num(r["overdraft_utilization"]),
        "late": num(r["late_share"]),
        "top1": num(r["top1_share"]),
        "current": num(r["current_ratio"]),
        "cash": num(r["cash"]),
        "events": 0,
        "trend": [],
    }


class Store:
    def __init__(self):
        print("loading firms…", flush=True)
        firms = pd.read_csv(f"{DATA}/firms.csv")
        self.firms = firms.set_index("firm_id")
        print("loading monthly…", flush=True)
        m = pd.read_csv(f"{DATA}/monthly_metrics.csv")
        self.monthly = m
        latest = m[m["month_index"] == AS_OF_MONTH_INDEX].copy()
        latest = latest.set_index("firm_id")
        print("loading events…", flush=True)
        ev = pd.read_csv(f"{DATA}/events.csv")
        ev["event_date"] = pd.to_datetime(ev["event_date"])
        self.events = ev[ev["event_date"] <= pd.Timestamp("2025-12-31")]
        print("loading counterparties…", flush=True)
        self.c = pd.read_csv(f"{DATA}/counterparties.csv")
        print("loading transactions…", flush=True)
        tx = pd.read_csv(f"{DATA}/transactions.csv", usecols=[
            "txn_id", "firm_id", "date", "month", "direction", "category",
            "counterparty_id", "counterparty_type", "amount", "days_late", "channel", "status",
        ])
        tx["date"] = pd.to_datetime(tx["date"])
        tx = tx = tx[(tx["date"] >= pd.Timestamp("2025-11-01")) & (tx["date"] <= pd.Timestamp("2025-12-31"))]
        self.tx = tx
        print("building rows…", flush=True)

        trend_by_id = (
            m[m["month_index"] <= AS_OF_MONTH_INDEX]
            .groupby("firm_id")["revenue"]
            .agg(list)
            .to_dict()
        )
        ev_counts = self.events.groupby("firm_id").size().to_dict()
        names = self.firms["name"].to_dict()

        self.clients = []
        self.by_id = {}
        for fid, r in latest.iterrows():
            sc = risk_score(r)
            zl, zc = zone_of(sc)
            row = compact_row(fid, r)
            row["name"] = names.get(fid, "")
            row["score"] = sc
            row["zone"] = zl
            row["zone_code"] = zc
            row["events"] = int(ev_counts.get(fid, 0))
            row["trend"] = [round(num(x), 0) for x in trend_by_id.get(fid, [])[-12:]]
            row["signals"] = build_signals(r)
            self.clients.append(row)
            self.by_id[fid] = row

        self.clients.sort(key=lambda x: -x["score"])
        self._aggregate()
        print("ready:", len(self.clients), "clients", flush=True)

    def _aggregate(self):
        hist = [b for b in self.clients]
        n = len(hist)
        self.portfolio = {
            "total": n,
            "critical": sum(1 for x in hist if x["zone_code"] == "critical"),
            "high": sum(1 for x in hist if x["zone_code"] in ("critical", "high")),
            "watch": sum(1 for x in hist if x["zone_code"] in ("watch", "elevated", "high", "critical")),
            "avg_score": round(sum(x["score"] for x in hist) / max(1, n), 1),
            "revenue": round(sum(x["revenue"] for x in hist), 0),
            "events": int(len(self.events)),
            "risk_revenue": round(sum(x["revenue"] for x in hist if x["score"] >= 45), 0),
        }
        self.ones = [
            {"name": x["name"], "id": x["id"], "score": x["score"], "zone": x["zone"]}
            for x in hist[:8]
        ]

    def client_meta(self, fid):
        x = self.by_id.get(fid)
        if not x:
            return None
        return x

    def client_detail(self, fid):
        if fid not in self.by_id:
            return None
        r = self.by_id[fid]
        hist = self.monthly[(self.monthly["firm_id"] == fid) &
                            (self.monthly["month_index"] <= AS_OF_MONTH_INDEX)]
        hist = hist.tail(24)
        series = []
        for _, x in hist.iterrows():
            series.append({
                "month": x["month"],
                "revenue": num(x["revenue"]),
                "receipts": num(x["cash_receipts"]),
                "cash": num(x["cash"]),
                "runway": num(x["runway_days"]),
                "fixed": num(x["fixed_expense_ratio"]),
                "dso": num(x["dso_days"]),
                "overdraft": num(x["overdraft_utilization"]),
                "late": num(x["late_share"]),
                "score": num(x["default_next_12m"]),
            })
        evs = self.events[self.events["firm_id"] == fid].sort_values("event_date", ascending=False).head(6)
        events = [{
            "date": e["event_date"].strftime("%d.%m.%Y"),
            "type": e["event_type"],
            "source": e["source"],
            "amount": num(e["amount"]),
            "text": e["description"],
        } for _, e in evs.iterrows()]
        tp = self.c[self.c["firm_id"] == fid].sort_values("share", ascending=False).head(5)
        clients = [{
            "id": x["client_id"],
            "name": x["client_id"],
            "industry": x["industry"],
            "share": x["share"],
            "revenue": num(x["annual_revenue"]),
        } for _, x in tp.iterrows()]
        txs = self.tx[self.tx["firm_id"] == fid].sort_values("date", ascending=False).head(8)
        transactions = [{
            "date": x["date"].strftime("%d.%m"),
            "amount": num(x["amount"]),
            "direction": x["direction"],
            "category": x["category"],
            "counterparty": x["counterparty_id"],
            "late": int(x["days_late"]),
        } for _, x in txs.iterrows()]
        last = self.monthly[(self.monthly["firm_id"] == fid) & (self.monthly["month_index"] == AS_OF_MONTH_INDEX)].iloc[0]
        return {
            "meta": r,
            "series": series,
            "signals": r["signals"],
            "events": events,
            "counterparties": clients,
            "transactions": transactions,
            "balance": {
                "assets": num(last["assets"]),
                "liabilities": num(last["liabilities"]),
                "equity": num(last["equity"]),
                "cash": num(last["cash"]),
                "receivables": num(last["receivables"]),
                "debt": num(last["debt"]),
                "current_assets": num(last["current_assets"]),
                "current_liabilities": num(last["current_liabilities"]),
                "revenue": num(last["revenue"]),
                "ebitda": num(last["ebitda"]),
                "ocf": num(last["ocf"]),
                "fixed": num(last["fixed_expense_ratio"]),
                "dscr": num(last["dscr"]),
                "current": num(last["current_ratio"]),
                "equity_ratio": num(last["equity_ratio"]),
            },
            "as_of": as_of_label(),
        }

    def bootstrap(self):
        return {
            "as_of": as_of_label(),
            "portfolio": self.portfolio,
            "clients": self.clients,
            "top": self.ones,
            "industries": self._industries(),
            "zones": [{"key": n, "label": c, "count": sum(1 for x in self.clients if x["zone_code"] == n)}
                      for n, c in [("critical", "Критический"), ("high", "Высокий"),
                                   ("elevated", "Повышенный"), ("watch", "Наблюдение"),
                                   ("stable", "Устойчивый")]],
        }

    def _industries(self):
        out = {}
        for x in self.clients:
            d = out.setdefault(x["industry"], {"count": 0, "score": 0.0, "high": 0})
            d["count"] += 1
            d["score"] += x["score"]
            if x["score"] >= 45:
                d["high"] += 1
        return sorted([{"industry": k, "count": v["count"],
                        "avg_score": round(v["score"] / v["count"], 1),
                        "high": v["high"]} for k, v in out.items()],
                      key=lambda d: -d["avg_score"])


def as_of_label():
    return "31 декабря 2025"


STORE = None


class Handler(BaseHTTPRequestHandler):
    server_version = "TideMonitor/1.0"

    def _send(self, code, body, ctype="application/json; charset=utf-8"):
        if isinstance(body, str):
            body = body.encode("utf-8")
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-store")
        self.send_header("Access-Control-Allow-Origin", "*")
        self.end_headers()
        self.wfile.write(body)

    def _json(self, obj, code=200):
        self._send(code, json.dumps(obj, ensure_ascii=False, default=str), "application/json; charset=utf-8")

    def do_GET(self):
        path = self.path.split("?")[0]
        try:
            if path == "/api/bootstrap":
                self._json(STORE.bootstrap())
                return
            if path.startswith("/api/client/"):
                fid = unquote(path.split("/api/client/", 1)[1])
                d = STORE.client_detail(fid)
                if d is None:
                    self._json({"error": "not found"}, 404)
                else:
                    self._json(d)
                return
            if path == "/":
                path = "/index.html"
            p = os.path.join(ROOT, "static", path.lstrip("/"))
            if not os.path.isfile(p):
                self._send(404, "not found", "text/plain; charset=utf-8")
                return
            ctype = {
                ".html": "text/html; charset=utf-8",
                ".css": "text/css; charset=utf-8",
                ".js": "application/javascript; charset=utf-8",
                ".svg": "image/svg+xml",
                ".json": "application/json; charset=utf-8",
            }.get(os.path.splitext(p)[1], "application/octet-stream")
            with open(p, "rb") as fh:
                self._send(200, fh.read(), ctype)
        except Exception as e:
            import traceback
            traceback.print_exc()
            self._json({"error": str(e)}, 500)

    def log_message(self, fmt, *args):
        pass


if __name__ == "__main__":
    STORE = Store()
    print("ready", flush=True)
    port = int(os.environ.get("PORT", "3001"))
    srv = ThreadingHTTPServer(("0.0.0.0", port), Handler)
    srv.serve_forever()
