from __future__ import annotations

import hashlib
import json
import sqlite3
from typing import Any, Dict, List


def _snapshot_queries(conn: sqlite3.Connection) -> Dict[str, Any]:
    appts = conn.execute(
        "SELECT id, status, start_dt FROM store_appointments ORDER BY id"
    ).fetchall()
    followups = conn.execute(
        "SELECT id, member_id, next_followup_date FROM store_followups ORDER BY id"
    ).fetchall()
    return {
        "appointments": [dict(r) for r in appts],
        "followups": [dict(r) for r in followups],
    }


def compute_snapshot_hash(conn: sqlite3.Connection) -> str:
    payload = _snapshot_queries(conn)
    raw = json.dumps(payload, sort_keys=True, ensure_ascii=False)
    return hashlib.sha256(raw.encode("utf-8")).hexdigest()


def check_db_changes(conn: sqlite3.Connection) -> Dict[str, Any]:
    current = compute_snapshot_hash(conn)
    row = conn.execute(
        "SELECT value_json FROM store_meta WHERE key='reminder_snapshot_hash'"
    ).fetchone()
    previous = ""
    if row:
        try:
            previous = json.loads(row["value_json"] or '""')
        except json.JSONDecodeError:
            previous = str(row["value_json"])
    changed = bool(previous) and previous != current
    return {
        "changed": changed,
        "previous_hash": previous or None,
        "current_hash": current,
    }


def save_snapshot_hash(conn: sqlite3.Connection) -> str:
    current = compute_snapshot_hash(conn)
    conn.execute(
        """INSERT INTO store_meta (key, value_json) VALUES ('reminder_snapshot_hash', ?)
           ON CONFLICT(key) DO UPDATE SET value_json=excluded.value_json""",
        (json.dumps(current),),
    )
    conn.commit()
    return current


def summarize_changes(conn: sqlite3.Connection) -> List[str]:
    check = check_db_changes(conn)
    if not check["changed"]:
        return []
    appt_n = conn.execute("SELECT COUNT(*) FROM store_appointments WHERE status='scheduled'").fetchone()[0]
    fu_n = conn.execute(
        "SELECT COUNT(*) FROM store_followups WHERE next_followup_date IS NOT NULL"
    ).fetchone()[0]
    return [
        "检测到经营数据变化：scheduled 预约 {} 条，有效跟进 {} 条。建议运行 daily-summary。".format(
            appt_n, fu_n
        )
    ]
