#!/usr/bin/env python3
"""Aggregate insurance overview directly from shared insurance.sqlite3."""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any

SCRIPTS_DIR = Path(__file__).resolve().parent
if str(SCRIPTS_DIR) not in sys.path:
    sys.path.insert(0, str(SCRIPTS_DIR))

from insurance_customer_cli import db


def aggregate() -> dict[str, Any]:
    conn = db.connect()
    month = conn.execute("SELECT strftime('%Y-%m','now','localtime') AS m").fetchone()["m"]
    start = f"{month}-01 00:00:00"
    y, m = map(int, month.split("-"))
    end = f"{y + 1:04d}-01-01 00:00:00" if m == 12 else f"{y:04d}-{m + 1:02d}-01 00:00:00"

    customers_total = int(conn.execute("SELECT COUNT(*) AS n FROM customers WHERE status='active'").fetchone()["n"])
    hi_value = int(
        conn.execute(
            """
            SELECT COUNT(*) AS n FROM (
                SELECT c.id, COALESCE(SUM(p.premium),0) AS annual
                FROM customers c
                LEFT JOIN policies p ON p.customer_id=c.id AND p.status='active'
                WHERE c.status='active'
                GROUP BY c.id
                HAVING annual > 50000
            )
            """
        ).fetchone()["n"]
    )
    active = int(
        conn.execute(
            """
            SELECT COUNT(DISTINCT customer_id) AS n
            FROM followups
            WHERE created_at >= datetime('now','-30 days')
            """
        ).fetchone()["n"]
    )
    new = int(
        conn.execute(
            "SELECT COUNT(*) AS n FROM customers WHERE status='active' AND created_at >= datetime('now','-30 days')"
        ).fetchone()["n"]
    )
    dormant = int(
        conn.execute(
            """
            SELECT COUNT(*) AS n
            FROM customers c
            WHERE c.status='active'
              AND c.created_at < datetime('now','-60 days')
              AND COALESCE(
                    (SELECT MAX(f.created_at) FROM followups f WHERE f.customer_id=c.id),
                    c.created_at
                  ) < datetime('now','-60 days')
            """
        ).fetchone()["n"]
    )
    policies_total = int(conn.execute("SELECT COUNT(*) AS n FROM policies WHERE status='active'").fetchone()["n"])
    total_premium = float(
        conn.execute("SELECT COALESCE(SUM(premium),0) AS s FROM policies WHERE status='active'").fetchone()["s"]
    )
    products_total = int(conn.execute("SELECT COUNT(*) AS n FROM products WHERE status='active'").fetchone()["n"])
    renewal_30d = int(
        conn.execute(
            """
            SELECT COUNT(*) AS n FROM policies
            WHERE status='active'
              AND (
                (expire_date IS NOT NULL AND expire_date<>'' AND expire_date<=date('now','+30 days') AND expire_date>=date('now'))
                OR
                (next_pay_date IS NOT NULL AND next_pay_date<>'' AND next_pay_date<=date('now','+30 days') AND next_pay_date>=date('now'))
              )
            """
        ).fetchone()["n"]
    )
    followup_30d_lapsed = int(
        conn.execute(
            """
            SELECT COUNT(*) AS n
            FROM customers c
            WHERE c.status='active'
              AND COALESCE(
                    (SELECT MAX(f.created_at) FROM followups f WHERE f.customer_id=c.id),
                    c.created_at
                  ) < datetime('now','-30 days')
            """
        ).fetchone()["n"]
    )
    dormant_60d = dormant
    active_deals = int(
        conn.execute(
            "SELECT COUNT(*) AS n FROM deals WHERE stage IN ('在谈','方案中','议价')"
        ).fetchone()["n"]
    )
    this_month_target = float(
        (conn.execute("SELECT target_premium FROM monthly_targets WHERE month=?", (month,)).fetchone() or {"target_premium": 0})[
            "target_premium"
        ]
    )
    this_month_closed = float(
        conn.execute(
            """
            SELECT COALESCE(SUM(COALESCE(actual_premium, estimated_premium, 0)),0) AS s
            FROM deals
            WHERE stage='已成交' AND closed_at >= ? AND closed_at < ?
            """,
            (start, end),
        ).fetchone()["s"]
    )
    this_month_forecast = float(
        conn.execute(
            """
            SELECT COALESCE(SUM(
                CASE
                    WHEN stage='在谈' THEN estimated_premium * 0.20
                    WHEN stage='方案中' THEN estimated_premium * 0.50
                    WHEN stage='议价' THEN estimated_premium * 0.80
                    ELSE 0
                END
            ),0) AS s
            FROM deals
            """
        ).fetchone()["s"]
    )

    overview = {
        "customers_total": customers_total,
        "hi_value": hi_value,
        "active": active,
        "dormant": dormant,
        "new": new,
        "policies_total": policies_total,
        "total_premium": total_premium,
        "products_total": products_total,
        "renewal_30d": renewal_30d,
        "followup_30d_lapsed": followup_30d_lapsed,
        "dormant_60d": dormant_60d,
        "this_month": month,
        "active_deals": active_deals,
        "this_month_target": this_month_target,
        "this_month_closed": this_month_closed,
        "this_month_forecast": this_month_forecast,
    }

    md_lines: list[str] = []
    month_label = overview.get("this_month", "")
    md_lines.append(f"🛡️ **经营概览（{month_label}）**" if month_label else "🛡️ **经营概览**")
    md_lines.append("")
    md_lines.append(
        f"👥 客户：{overview['customers_total']}人（高净值{overview['hi_value']} / "
        f"活跃{overview['active']} / 沉睡{overview['dormant']} / 新客{overview['new']}）"
    )
    md_lines.append(
        f"📋 保单：{overview['policies_total']}份（总保费约¥{overview['total_premium']:,.0f}）"
    )
    md_lines.append(f"📦 产品库：{overview['products_total']} 款")
    md_lines.append(f"⏰ 本月续保：{overview['renewal_30d']}份 30 天内到期")
    md_lines.append(
        f"🎯 本月目标：保费¥{overview['this_month_target']:,.0f} | "
        f"已完成：¥{overview['this_month_closed']:,.0f} | "
        f"在谈预估：¥{overview['this_month_forecast']:,.0f} | "
        f"在谈商机：{overview['active_deals']}单"
    )
    md_lines.append("")
    md_lines.append("⚠️ 待处理：")
    md_lines.append(f"- {overview['renewal_30d']} 份保单 30 天内到期")
    md_lines.append(f"- {overview['followup_30d_lapsed']} 位客户超 30 天未联系")
    md_lines.append(f"- {overview['dormant_60d']} 位客户超 60 天未联系（沉睡）")

    conn.close()
    return {"ok": True, "overview": overview, "skills": {"source": "shared-db"}, "markdown": "\n".join(md_lines)}


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(prog="dashboard_all")
    parser.add_argument("--json", action="store_true",
                        help="只输出 JSON（默认就是 JSON；保留参数对齐子命令风格）")
    parser.add_argument("--md", action="store_true",
                        help="只打印 markdown 卡片（不打 JSON）")
    args = parser.parse_args(argv)
    try:
        sys.stdout.reconfigure(encoding="utf-8")
        sys.stderr.reconfigure(encoding="utf-8")
    except (AttributeError, OSError):
        pass
    data = aggregate()
    if args.md:
        print(data["markdown"])
    else:
        print(json.dumps(data, ensure_ascii=False, indent=2))
    return 0


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