"""Wallet and card commands."""

from __future__ import annotations

import argparse
import json
import time
from datetime import datetime, timedelta

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_error, emit_need_confirm, emit_ok

from store_customer_lib.common import SKILL


def cmd_balance_recharge(args: argparse.Namespace) -> int:
    if not args.yes:
        emit_need_confirm({"action": "balance-recharge", "member_id": args.member_id, "amount": args.amount})
        return 0
    t0 = time.perf_counter()
    conn = connect()
    bonus = float(args.bonus or 0)
    amt = float(args.amount)
    conn.execute("BEGIN IMMEDIATE")
    try:
        conn.execute(
            """UPDATE store_wallet SET balance=balance+?, total_recharge=total_recharge+?,
               updated_at=datetime('now','localtime') WHERE member_id=?""",
            (amt + bonus, amt, args.member_id),
        )
        conn.execute(
            "INSERT INTO store_transactions (member_id, type, amount, meta_json) VALUES (?,?,?,?)",
            (args.member_id, "recharge", amt, json.dumps({"bonus": bonus}, ensure_ascii=False)),
        )
        commit_with_log(
            conn, args, skill=SKILL, command="balance-recharge", op="update", table_name="store_wallet",
            entity_id=args.member_id, after_json={"member_id": args.member_id},
            duration_ms=int((time.perf_counter() - t0) * 1000),
        )
    except Exception:
        conn.rollback()
        raise
    emit_ok({"member_id": args.member_id})
    return 0


def cmd_balance_query(args: argparse.Namespace) -> int:
    t0 = time.perf_counter()
    conn = connect()
    row = conn.execute("SELECT * FROM store_wallet WHERE member_id=?", (args.member_id,)).fetchone()
    log_read(
        conn, args, skill=SKILL, command="balance-query", table_name="store_wallet",
        entity_id=args.member_id, duration_ms=int((time.perf_counter() - t0) * 1000),
    )
    emit_ok({"wallet": dict(row) if row else None})
    return 0


def cmd_card_open(args: argparse.Namespace) -> int:
    if not args.yes:
        emit_need_confirm({"action": "card-open", "member_id": args.member_id, "name": args.name})
        return 0
    t0 = time.perf_counter()
    conn = connect()
    cid = args.card_id or next_id(conn, "C", "store_cards")
    conn.execute("BEGIN IMMEDIATE")
    try:
        conn.execute(
            """INSERT INTO store_cards (id, member_id, name, service_name, total_times, price, expire_date)
               VALUES (?,?,?,?,?,?,?)""",
            (cid, args.member_id, args.name, args.service or None, int(args.times), float(args.price), args.expire or None),
        )
        conn.execute(
            "INSERT INTO store_transactions (member_id, type, amount, meta_json) VALUES (?,?,?,?)",
            (args.member_id, "card_purchase", float(args.price), json.dumps({"card_id": cid}, ensure_ascii=False)),
        )
        commit_with_log(
            conn, args, skill=SKILL, command="card-open", op="create", table_name="store_cards",
            entity_id=cid, after_json={"card_id": cid},
            duration_ms=int((time.perf_counter() - t0) * 1000),
        )
    except Exception:
        conn.rollback()
        raise
    emit_ok({"card_id": cid})
    return 0


def cmd_card_query(args: argparse.Namespace) -> int:
    t0 = time.perf_counter()
    conn = connect()
    rows = [dict(r) for r in conn.execute(
        "SELECT * FROM store_cards WHERE member_id=? AND status='active'", (args.member_id,)
    )]
    log_read(
        conn, args, skill=SKILL, command="card-query", table_name="store_cards",
        entity_id=args.member_id, duration_ms=int((time.perf_counter() - t0) * 1000),
    )
    emit_ok({"cards": rows})
    return 0


def cmd_card_expiring(args: argparse.Namespace) -> int:
    t0 = time.perf_counter()
    days = int(args.days)
    end = (datetime.now().date() + timedelta(days=days)).isoformat()
    conn = connect()
    rows = [dict(r) for r in conn.execute(
        """SELECT * FROM store_cards WHERE status='active'
           AND used_times < total_times
           AND expire_date IS NOT NULL AND expire_date != ''
           AND expire_date <= ? ORDER BY expire_date, id""",
        (end,),
    )]
    log_read(
        conn, args, skill=SKILL, command="card-expiring", table_name="store_cards",
        duration_ms=int((time.perf_counter() - t0) * 1000),
    )
    emit_ok({"cards": rows, "count": len(rows), "days": days})
    return 0
