"""Follow-up commands."""

from __future__ import annotations

import argparse
import time
from datetime import datetime
from typing import Any, List

from store_db.db import connect
from store_db.ids import next_id
from store_db.operation_log import commit_with_log, log_read
from store_db.response import emit_ok

from store_customer_lib.common import SKILL


def cmd_followup_add(args: argparse.Namespace) -> int:
    t0 = time.perf_counter()
    conn = connect()
    fid = args.followup_id or next_id(conn, "F", "store_followups")
    conn.execute(
        """INSERT INTO store_followups (id, member_id, content, contact_at, next_followup_date)
           VALUES (?,?,?,?,?)""",
        (fid, args.member_id, args.content or "", args.contact_at or "", args.next_followup_date),
    )
    commit_with_log(
        conn, args, skill=SKILL, command="followup-add", op="create", table_name="store_followups",
        entity_id=fid, duration_ms=int((time.perf_counter() - t0) * 1000),
    )
    emit_ok({"followup_id": fid, "member_id": args.member_id})
    return 0


def cmd_followup_query(args: argparse.Namespace) -> int:
    t0 = time.perf_counter()
    conn = connect()
    q = "SELECT * FROM store_followups WHERE 1=1"
    params: List[Any] = []
    if args.member_id:
        q += " AND member_id=?"
        params.append(args.member_id)
    if args.due_date:
        q += " AND next_followup_date=?"
        params.append(args.due_date)
    q += " ORDER BY next_followup_date, id"
    rows = [dict(r) for r in conn.execute(q, params)]
    log_read(
        conn, args, skill=SKILL, command="followup-query", table_name="store_followups",
        duration_ms=int((time.perf_counter() - t0) * 1000),
    )
    emit_ok({"followups": rows, "count": len(rows)})
    return 0


def cmd_followup_due(args: argparse.Namespace) -> int:
    args.due_date = args.date or datetime.now().strftime("%Y-%m-%d")
    args.member_id = None
    return cmd_followup_query(args)
