from __future__ import annotations

import argparse
import json
import sys
import time
from datetime import datetime

from store_db.db import connect
from store_db.operation_log import log_read
from store_db.response import emit_ok
from store_schedule_lib.daily_summary import build_daily_summary, pending_one_liners

from store_reporting_lib.metrics import (
    compute_period_metrics,
    format_report_md,
    period_bounds,
    report_by_service,
    staff_ranking,
)

SKILL = "store-reporting"


def _report_period(args: argparse.Namespace, period: str) -> int:
    t0 = time.perf_counter()
    conn = connect()
    ref = args.date or datetime.now().strftime("%Y-%m-%d")
    start, end = period_bounds(period, ref)
    metrics = compute_period_metrics(conn, start, end)
    title = {"day": "日报", "week": "周报", "month": "月报"}[period]
    body: dict = {"period": period, "metrics": metrics}
    if args.md:
        body["markdown"] = format_report_md(
            metrics, title=title, show_repeat=(period == "month")
        )
    command = {"day": "report-day", "week": "report-week", "month": "report-month"}[period]
    log_read(
        conn, args, skill=SKILL, command=command, table_name="store_orders",
        duration_ms=int((time.perf_counter() - t0) * 1000),
    )
    emit_ok(body)
    return 0


def cmd_dashboard(args: argparse.Namespace) -> int:
    t0 = time.perf_counter()
    conn = connect()
    date = args.date or datetime.now().strftime("%Y-%m-%d")
    metrics = compute_period_metrics(conn, date, date)
    summary = build_daily_summary(conn, date)
    pending = pending_one_liners(summary["blocks"])

    md_lines = [
        f"🏪 **门店概览（{date}）**",
        "",
        "💰 今日经营",
        f"· 营收 ¥{metrics['revenue']} | 现金实收 ¥{metrics['cash']} | 储值核销 ¥{metrics['stored_value']} | 次卡核销 ¥{metrics['card_use_revenue']}",
        f"· 到店 {metrics['visits']} 人 | 客单 ¥{metrics['avg_ticket']}",
        "",
        "⏰ 待处理",
        *pending,
    ]
    markdown = "\n".join(md_lines)

    body = {
        "date": date,
        "metrics": metrics,
        "pending": summary["blocks"],
    }
    if args.json:
        body["blocks"] = summary["blocks"]
    if args.md or (not args.json):
        body["markdown"] = markdown
    log_read(
        conn, args, skill=SKILL, command="dashboard", table_name="store_orders",
        duration_ms=int((time.perf_counter() - t0) * 1000),
    )
    emit_ok(body)
    return 0


def cmd_report_staff(args: argparse.Namespace) -> int:
    t0 = time.perf_counter()
    conn = connect()
    month = args.month or datetime.now().strftime("%Y-%m")
    ranking = staff_ranking(conn, month)
    log_read(
        conn, args, skill=SKILL, command="report-staff", table_name="staff_performance",
        duration_ms=int((time.perf_counter() - t0) * 1000),
    )
    emit_ok({"month": month, "ranking": ranking})
    return 0


def cmd_report_by_service(args: argparse.Namespace) -> int:
    t0 = time.perf_counter()
    conn = connect()
    month = args.month or datetime.now().strftime("%Y-%m")
    rows = report_by_service(conn, month)
    body: dict = {"month": month, "services": rows}
    if args.md:
        lines = [f"# 项目营收（{month}）", ""]
        for r in rows:
            lines.append(f"· {r['service']}：{r['count']} 次 | ¥{r['revenue']}")
        if not rows:
            lines.append("无")
        body["markdown"] = "\n".join(lines)
    log_read(
        conn, args, skill=SKILL, command="report-by-service", table_name="store_orders",
        duration_ms=int((time.perf_counter() - t0) * 1000),
    )
    emit_ok(body)
    return 0


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(description="Store reporting CLI")
    sub = p.add_subparsers(dest="cmd", required=True)

    s = sub.add_parser("dashboard")
    s.add_argument("--date")
    s.add_argument("--md", action="store_true")
    s.add_argument("--json", action="store_true")
    s.add_argument("--session-id")
    s.set_defaults(func=cmd_dashboard)

    for name, period in [("report-day", "day"), ("report-week", "week"), ("report-month", "month")]:
        s = sub.add_parser(name)
        s.add_argument("--date")
        s.add_argument("--md", action="store_true")
        s.add_argument("--session-id")
        s.set_defaults(func=lambda a, p=period: _report_period(a, p))

    s = sub.add_parser("report-staff")
    s.add_argument("--month")
    s.add_argument("--session-id")
    s.set_defaults(func=cmd_report_staff)

    s = sub.add_parser("report-by-service")
    s.add_argument("--month")
    s.add_argument("--md", action="store_true")
    s.add_argument("--session-id")
    s.set_defaults(func=cmd_report_by_service)

    return p


def main() -> int:
    args = build_parser().parse_args()
    return int(args.func(args))


if __name__ == "__main__":
    sys.exit(main())
