#!/usr/bin/env python3
"""Smoke test for dashboard_all.py — seeds tiny data into all 4 skill DBs
and verifies the aggregated card.

Run from anywhere::

    python3 path/to/insurance-customer-policy/src/scripts/test_dashboard_all.py
"""
from __future__ import annotations

import json
import os
import subprocess
import sys
import tempfile
from datetime import datetime, timedelta
from pathlib import Path

HERE = Path(__file__).resolve().parent
SKILLS_ROOT = HERE.parent.parent.parent

CUSTOMER_PKG = SKILLS_ROOT / "insurance-customer-policy" / "src" / "src"
PRODUCT_PKG = SKILLS_ROOT / "insurance-product-analysis" / "src" / "src"
SCHEDULE_PKG = SKILLS_ROOT / "insurance-schedule-renewal" / "src" / "src"
PIPELINE_PKG = SKILLS_ROOT / "insurance-sales-pipeline" / "src" / "src"


def call(pkg: Path, module: str, *args: str) -> dict:
    env = {**os.environ, "PYTHONPATH": str(pkg), "PYTHONIOENCODING": "utf-8"}
    r = subprocess.run([sys.executable, "-m", module, *args],
                       env=env, capture_output=True, text=True,
                       encoding="utf-8", timeout=60)
    if r.returncode not in (0, 1):
        raise SystemExit(f"rc={r.returncode} module={module} args={args}\n{r.stdout}\n{r.stderr}")
    return json.loads(r.stdout.strip() or "{}")


def main() -> int:
    tmp = tempfile.mkdtemp(prefix="ins_dash_smoke_")
    os.environ["INSURANCE_CUSTOMER_DB_PATH"] = str(Path(tmp) / "customer.sqlite3")
    os.environ["INSURANCE_PRODUCT_DB_PATH"] = str(Path(tmp) / "product.sqlite3")
    os.environ["INSURANCE_SCHEDULE_DB_PATH"] = str(Path(tmp) / "reminders.sqlite3")
    os.environ["INSURANCE_PIPELINE_DB_PATH"] = str(Path(tmp) / "pipeline.sqlite3")

    today = datetime.now()
    in_15 = (today + timedelta(days=15)).strftime("%Y-%m-%d")

    print("[seed] customers + policies")
    for i, (name, age, income) in enumerate([("张先生", 35, 300000),
                                             ("李女士", 40, 100000),
                                             ("王先生", 50, 600000)], 1):
        call(CUSTOMER_PKG, "insurance_customer_cli",
             "customer-add", "--name", name, "--phone", f"138{i:08d}",
             "--age", str(age), "--income", str(income))
    call(CUSTOMER_PKG, "insurance_customer_cli",
         "policy-add", "--customer-id", "C001", "--company", "A", "--product", "重疾",
         "--type", "重疾险", "--coverage", "500000", "--premium", "8000",
         "--effective-date", "2024-01-01", "--expire-date", in_15)
    call(CUSTOMER_PKG, "insurance_customer_cli",
         "policy-add", "--customer-id", "C003", "--company", "B", "--product", "年金",
         "--type", "养老险", "--coverage", "1000000", "--premium", "60000",
         "--effective-date", "2024-01-01")

    print("[seed] product")
    call(PRODUCT_PKG, "insurance_product_cli",
         "product-add", "--name", "XX重疾2024", "--company", "A", "--type", "重疾险")

    print("[seed] deal + target")
    call(PIPELINE_PKG, "insurance_pipeline_cli",
         "deal-add", "--customer-id", "C001", "--product-type", "重疾险",
         "--stage", "在谈", "--estimated-premium", "8000")
    month = today.strftime("%Y-%m")
    call(PIPELINE_PKG, "insurance_pipeline_cli",
         "target-track", "--month", month, "--target", "100000")

    print("[run] dashboard_all.py --json")
    r = subprocess.run([sys.executable, str(HERE / "dashboard_all.py")],
                       env={**os.environ, "PYTHONIOENCODING": "utf-8"},
                       capture_output=True, text=True, encoding="utf-8", timeout=60)
    if r.returncode != 0:
        raise SystemExit(f"dashboard_all.py rc={r.returncode}\n{r.stdout}\n{r.stderr}")
    data = json.loads(r.stdout)
    assert data["ok"], data
    ov = data["overview"]
    print(f"  overview customers={ov['customers_total']} policies={ov['policies_total']} "
          f"premium={ov['total_premium']} products={ov['products_total']} renewal_30d={ov['renewal_30d']} "
          f"active_deals={ov['active_deals']} target={ov['this_month_target']}")
    assert ov["customers_total"] == 3, ov
    assert ov["policies_total"] == 2, ov
    assert ov["total_premium"] == 68000.0, ov
    assert ov["products_total"] == 1, ov
    assert ov["renewal_30d"] >= 1, ov
    assert ov["active_deals"] >= 1, ov
    assert ov["this_month_target"] == 100000, ov
    assert ov["hi_value"] == 1, ov  # C003 premium=60000 > 50000
    # markdown sanity
    assert "经营概览" in data["markdown"]
    assert "客户：3" in data["markdown"]

    print("[run] dashboard_all.py --md")
    r2 = subprocess.run([sys.executable, str(HERE / "dashboard_all.py"), "--md"],
                        env={**os.environ, "PYTHONIOENCODING": "utf-8"},
                        capture_output=True, text=True, encoding="utf-8", timeout=60)
    assert r2.returncode == 0
    assert "经营概览" in r2.stdout
    assert "保单" in r2.stdout

    print("ALL OK")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
