from __future__ import annotations

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

from store_schedule_lib.change_monitor import check_db_changes
from store_schedule_lib.conflicts import detect_operational_conflicts as detect_conflicts
from store_schedule_lib.config_loader import threshold_int
from store_schedule_lib.queries import (
    BLOCK_SPECS,
    REMINDER_TYPES,
    mark_items_sent,
    run_query,
)


def _format_block(title: str, items: List[Dict[str, Any]]) -> str:
    lines = [title]
    if not items:
        lines.append("无")
        return "\n".join(lines)
    for it in items:
        parts = ["{}={}".format(k, v) for k, v in it.items()]
        lines.append("· " + " | ".join(parts))
    return "\n".join(lines)


def build_daily_summary(
    conn: sqlite3.Connection,
    date: str,
    *,
    mark_sent: bool = False,
    days: Optional[int] = None,
    include_conflicts: bool = True,
    include_changes: bool = True,
) -> Dict[str, Any]:
    blocks: List[Dict[str, Any]] = []
    md_parts: List[str] = ["# 今日提醒（{}）".format(date), ""]

    card_days = days if days is not None else threshold_int(conn, "card_expiring_days", 30)
    member_due_days = threshold_int(conn, "member_due_days", 30)

    for rtype, title, _ in BLOCK_SPECS:
        if rtype == "card_expiring":
            items = run_query(conn, rtype, date, days=card_days)
            span = card_days
        elif rtype == "member_due":
            items = run_query(conn, rtype, date, days=member_due_days)
            span = member_due_days
        else:
            items = run_query(conn, rtype, date)
            span = None
        blocks.append({"type": rtype, "count": len(items), "items": items})
        md_parts.append(_format_block(title, items))
        md_parts.append("")
        if mark_sent and items:
            mark_items_sent(conn, rtype, date, items, days=span)

    conflicts: List[Dict[str, Any]] = []
    if include_conflicts:
        conflicts = detect_conflicts(conn, date)
        if conflicts:
            blocks.append({"type": "conflicts", "count": len(conflicts), "items": conflicts})
            md_parts.append("⚠️ 经营冲突")
            for c in conflicts:
                md_parts.append("· {}".format(c.get("message", "")))
            md_parts.append("")

    changes: Dict[str, Any] = {}
    if include_changes:
        changes = check_db_changes(conn)
        if changes.get("changed"):
            md_parts.append("📌 经营数据自上次快照以来有变化，建议核对预约与跟进。")
            md_parts.append("")

    markdown = "\n".join(md_parts).strip()
    body: Dict[str, Any] = {"date": date, "blocks": blocks, "markdown": markdown}
    if conflicts:
        body["conflicts"] = conflicts
    if changes:
        body["changes"] = changes
    return body


def pending_one_liners(blocks: List[Dict[str, Any]]) -> List[str]:
    title_map = {t: title for t, title, _ in BLOCK_SPECS}
    title_map["conflicts"] = "⚠️ 经营冲突"
    lines: List[str] = []
    for b in blocks:
        if b["type"] == "conflicts":
            continue
        title = title_map.get(b["type"], b["type"])
        lines.append("· {}：{} 条".format(title, b.get("count", 0)))
    return lines
