"""Shared helpers for store-customer."""

from __future__ import annotations

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

SKILL = "store-customer"


def parse_fields_json(raw: str) -> Dict[str, Any]:
    try:
        data = json.loads(raw or "{}")
        return data if isinstance(data, dict) else {}
    except (json.JSONDecodeError, TypeError):
        return {}


def validate_birthday_month(mm: str) -> Optional[str]:
    try:
        n = int(mm)
        if 1 <= n <= 12:
            return f"{n:02d}"
    except ValueError:
        pass
    return None


def attach_member_extras(conn: sqlite3.Connection, rows: List[dict], args: Any) -> None:
    if getattr(args, "with_wallet", False):
        for r in rows:
            w = conn.execute("SELECT * FROM store_wallet WHERE member_id=?", (r["id"],)).fetchone()
            r["wallet"] = dict(w) if w else None
    if getattr(args, "with_cards", False):
        for r in rows:
            cards = conn.execute(
                "SELECT * FROM store_cards WHERE member_id=? AND status='active'", (r["id"],)
            ).fetchall()
            r["cards"] = [dict(c) for c in cards]
    if getattr(args, "with_profile", False):
        for r in rows:
            prof = conn.execute(
                "SELECT last_visit_at, visit_count, fav_service FROM store_consumption_log WHERE member_id=?",
                (r["id"],),
            ).fetchone()
            r["profile"] = dict(prof) if prof else None
    if getattr(args, "with_fields", False):
        for r in rows:
            r["fields"] = parse_fields_json(r.get("fields_json") or "{}")


def delete_blocked(conn: sqlite3.Connection, member_id: str) -> Optional[str]:
    appt = conn.execute(
        "SELECT id FROM store_appointments WHERE member_id=? AND status='scheduled' LIMIT 1",
        (member_id,),
    ).fetchone()
    if appt:
        return "scheduled appointment exists"
    order = conn.execute(
        """SELECT id FROM store_orders WHERE member_id=? AND status IN ('draft','confirmed','in_progress') LIMIT 1""",
        (member_id,),
    ).fetchone()
    if order:
        return "open order exists"
    card = conn.execute(
        """SELECT id FROM store_cards WHERE member_id=? AND status='active'
           AND used_times < total_times AND (expire_date IS NULL OR expire_date >= date('now')) LIMIT 1""",
        (member_id,),
    ).fetchone()
    if card:
        return "active card with remaining times"
    return None
