"""Import, export, and convenience query commands."""

from __future__ import annotations

import argparse
import json
import time
from typing import List

from store_db.db import connect
from store_db.operation_log import commit_with_log, log_read
from store_db.response import emit_error, emit_need_confirm, emit_ok

from store_customer_lib.common import SKILL, attach_member_extras
from store_customer_lib.import_export.exporter import export_rows, flatten_members
from store_customer_lib.import_export.service import run_import
from store_customer_lib.query_extras import query_birthdays, query_due


def cmd_import_preview(args: argparse.Namespace) -> int:
    t0 = time.perf_counter()
    conn = connect()
    try:
        summary = run_import(conn, args.path, commit=False)
    except ValueError as e:
        emit_error("import_failed", {"detail": str(e)})
    log_read(
        conn, args, skill=SKILL, command="import-preview", table_name="store_members",
        duration_ms=int((time.perf_counter() - t0) * 1000),
    )
    emit_ok({"preview": summary})
    return 0


def cmd_import_commit(args: argparse.Namespace) -> int:
    if not args.yes:
        emit_need_confirm({"action": "import-commit", "path": args.path})
        return 0
    t0 = time.perf_counter()
    conn = connect()
    try:
        summary = run_import(conn, args.path, commit=True)
    except ValueError as e:
        emit_error("import_failed", {"detail": str(e)})
    commit_with_log(
        conn, args, skill=SKILL, command="import-commit", op="create", table_name="store_members",
        after_json={"customer_count": summary.get("customer_count")},
        duration_ms=int((time.perf_counter() - t0) * 1000),
    )
    emit_ok({"imported": summary})
    return 0


def cmd_export_file(args: argparse.Namespace) -> int:
    t0 = time.perf_counter()
    conn = connect()
    clauses = ["status='active'"]
    params: List = []
    if args.member_id:
        clauses.append("id=?")
        params.append(args.member_id)
    sql = "SELECT * FROM store_members WHERE {} ORDER BY id".format(" AND ".join(clauses))
    rows = [dict(r) for r in conn.execute(sql, params)]
    attach_member_extras(conn, rows, args)
    labels = {
        r["field_key"]: r["label"]
        for r in conn.execute(
            "SELECT field_key, label FROM store_custom_field_defs WHERE entity='member'"
        )
    }
    flat = flatten_members(rows, labels)
    try:
        result = export_rows(flat, args.output)
    except ValueError as e:
        emit_error("export_failed", {"detail": str(e)})
    log_read(
        conn, args, skill=SKILL, command="export-file", table_name="store_members",
        duration_ms=int((time.perf_counter() - t0) * 1000),
    )
    emit_ok(result)
    return 0


def cmd_member_birthdays(args: argparse.Namespace) -> int:
    t0 = time.perf_counter()
    conn = connect()
    try:
        body = query_birthdays(conn, int(args.month), args.limit or 20, args)
    except ValueError:
        emit_error("invalid_query", {"month": args.month})
    log_read(
        conn, args, skill=SKILL, command="member-birthdays", table_name="store_members",
        duration_ms=int((time.perf_counter() - t0) * 1000),
    )
    emit_ok(body)
    return 0


def cmd_member_due(args: argparse.Namespace) -> int:
    t0 = time.perf_counter()
    conn = connect()
    body = query_due(conn, int(args.within_days), args.limit or 20, args)
    log_read(
        conn, args, skill=SKILL, command="member-due", table_name="store_members",
        duration_ms=int((time.perf_counter() - t0) * 1000),
    )
    emit_ok(body)
    return 0
