"""Shared-db read helpers for insurance-schedule-renewal."""
from __future__ import annotations

from insurance_schedule_cli import db


def policy_query(expire_before: str | None = None,
                 next_pay_before: str | None = None,
                 customer_id: str | None = None) -> dict:
    conn = db.connect()
    try:
        sql = "SELECT * FROM policies WHERE status='active'"
        vals: list[str] = []
        if customer_id:
            sql += " AND customer_id=?"
            vals.append(customer_id)
        if expire_before:
            sql += " AND expire_date<>'' AND expire_date IS NOT NULL AND expire_date<=?"
            vals.append(expire_before)
        if next_pay_before:
            sql += " AND next_pay_date<>'' AND next_pay_date IS NOT NULL AND next_pay_date<=?"
            vals.append(next_pay_before)
        sql += " ORDER BY effective_date DESC"
        rows = list(conn.execute(sql, tuple(vals)))
        return {"ok": True, "policies": [dict(r) for r in rows], "count": len(rows)}
    finally:
        conn.close()


def customer_query(customer_id: str | None = None) -> dict:
    conn = db.connect()
    try:
        if customer_id:
            rows = list(
                conn.execute("SELECT * FROM customers WHERE id=? AND status='active'", (customer_id,))
            )
        else:
            rows = list(conn.execute("SELECT * FROM customers WHERE status='active' ORDER BY created_at DESC"))
        return {"ok": True, "customers": [dict(r) for r in rows], "count": len(rows)}
    finally:
        conn.close()


def followup_query(customer_id: str | None = None, days: int | None = None) -> dict:
    conn = db.connect()
    try:
        if customer_id:
            rows = list(
                conn.execute(
                    "SELECT * FROM followups WHERE customer_id=? ORDER BY created_at DESC",
                    (customer_id,),
                )
            )
        elif days is not None:
            rows = list(
                conn.execute(
                    "SELECT * FROM followups WHERE created_at >= datetime('now', ?) ORDER BY created_at DESC",
                    (f"-{int(days)} days",),
                )
            )
        else:
            rows = list(conn.execute("SELECT * FROM followups ORDER BY created_at DESC"))
        return {"ok": True, "followups": [dict(r) for r in rows], "count": len(rows)}
    finally:
        conn.close()


def gap_analysis(customer_id: str) -> dict:
    conn = db.connect()
    try:
        row = conn.execute(
            "SELECT id, name FROM customers WHERE id=? AND status='active'",
            (customer_id,),
        ).fetchone()
        if not row:
            return {"ok": False, "error": "customer_not_found"}
        need_types = ["重疾险", "医疗险", "意外险", "寿险", "养老险", "教育金"]
        owned = {
            r["product_type"]
            for r in conn.execute(
                "SELECT DISTINCT product_type FROM policies WHERE customer_id=? AND status='active'",
                (customer_id,),
            )
            if r["product_type"]
        }
        result = {
            "customer_id": row["id"],
            "name": row["name"],
            "owned_types": sorted(owned),
            "gaps": [t for t in need_types if t not in owned],
        }
        return {"ok": True, "result": result}
    finally:
        conn.close()
