from __future__ import annotations

import sqlite3
from pathlib import Path
from typing import Any, Dict, List, Optional


def _catalog_services(conn: sqlite3.Connection, limit: int = 5) -> List[Dict[str, Any]]:
    rows = conn.execute(
        "SELECT name, price FROM catalog_services WHERE status='active' ORDER BY price DESC LIMIT ?",
        (limit,),
    ).fetchall()
    return [{"name": r["name"], "price": float(r["price"])} for r in rows]


def _playbook_path() -> Optional[str]:
    here = Path(__file__).resolve().parents[1]
    p = here / "references" / "playbook.md"
    return str(p) if p.is_file() else None


def _rhythm_7d() -> List[str]:
    return [
        "D-7：朋友圈预热 + 名单触达",
        "D-5：私信邀约 + 限时名额",
        "D-3：到店礼提醒",
        "D-1：最后名额倒计时",
        "D-Day：到店接待与加项推荐",
        "D+1：满意度回访",
        "D+7：复盘转化与二次跟进",
    ]


def _data_summary_md(
    segment: str,
    count: int,
    sample: str,
    main_services: List[Dict[str, Any]],
    festival: Optional[str],
) -> str:
    title = "# 活动数据摘要 · {}".format(segment)
    if festival:
        title += " · {}".format(festival)
    lines = [
        title,
        "",
        "目标客群：{}（{} 人）示例：{}".format(segment, count, sample),
        "主推项目：" + ", ".join(
            "{} ¥{}".format(s["name"], int(s["price"])) for s in main_services
        ),
        "",
        "文案与话术请按 playbooks/content-generation.md 生成，勿使用预制模板。",
        "复盘指标：预约数、到店核销率、活动客单价、沉睡唤醒率",
    ]
    return "\n".join(lines)


def build_campaign_suggest(
    conn: sqlite3.Connection,
    *,
    segment: str,
    service: Optional[str],
    festival: Optional[str],
    segment_data: Dict[str, List[Dict[str, Any]]],
) -> Dict[str, Any]:
    members = segment_data.get(segment) or segment_data.get("沉睡") or []
    count = len(members)
    services = _catalog_services(conn)
    if service:
        row = conn.execute(
            "SELECT name, price FROM catalog_services WHERE name=? AND status='active'",
            (service,),
        ).fetchone()
        main_services = [{"name": row["name"], "price": float(row["price"])}] if row else services[:2]
    else:
        main_services = services[:3]
    if not main_services:
        main_services = [{"name": "到店体验", "price": 0.0}]

    names = [m["name"] for m in members[:5]]
    sample = "、".join(names) if names else "（暂无名单，请先 segment-run）"

    plan = {
        "target_segment": segment,
        "target_count": count,
        "sample_members": names,
        "main_services": main_services,
        "channels": ["微信私聊", "朋友圈", "门店社群"],
        "metrics": ["预约数", "到店核销率", "活动客单价", "沉睡唤醒率"],
        "rhythm_7d": _rhythm_7d(),
        "playbook_path": _playbook_path(),
        "agent_instructions": "按 playbooks/content-generation.md 生成文案；勿使用预制话术",
    }
    if festival:
        plan["festival"] = festival
    plan["markdown"] = _data_summary_md(segment, count, sample, main_services, festival)
    return plan


def build_dormant_wake(
    conn: sqlite3.Connection,
    segment_data: Dict[str, List[Dict[str, Any]]],
) -> Dict[str, Any]:
    dormant = segment_data.get("沉睡") or []
    plan = build_campaign_suggest(
        conn,
        segment="沉睡客户",
        service=None,
        festival=None,
        segment_data={"沉睡客户": dormant, "沉睡": dormant},
    )
    plan["members"] = dormant[:50]
    plan["count"] = len(dormant)
    return plan
