"""Column mapping for member import."""

from __future__ import annotations

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

from store_db.field_defs import normalize_field_type
from store_customer_lib.import_export.normalizer import (
    clean_text,
    guess_value_type,
    is_blank,
    normalize_date,
    normalize_optional_text,
    normalize_phone,
    normalize_tags,
    stable_field_key,
)

BUILTIN_ALIASES = {
    "name": {"姓名", "名字", "客户名", "客户姓名", "name"},
    "phone": {"电话", "手机号", "手机", "联系电话", "联系方式", "mobile", "phone"},
    "birthday": {"生日", "出生日期", "birth", "birthday"},
    "due_date": {"到期日", "到期日期", "下次到期", "due_date"},
    "tags": {"标签", "分组", "tags"},
    "note": {"备注", "说明", "note", "notes"},
}

GROUPED_SUFFIXES = {"姓名", "性别", "生日", "出生日期", "手机", "手机号", "电话", "联系电话"}


def resolve_builtin(label: str) -> Optional[str]:
    key = clean_text(label).lower()
    for builtin, aliases in BUILTIN_ALIASES.items():
        if key in {a.lower() for a in aliases}:
            return builtin
    return None


def resolve_grouped_field(label: str) -> Optional[str]:
    text = clean_text(label).lower()
    if "_" in text:
        suffix = text.split("_", 1)[1]
        if suffix in {s.lower() for s in GROUPED_SUFFIXES}:
            if suffix in ("手机", "手机号", "电话", "联系电话"):
                return "phone"
            if suffix in ("生日", "出生日期"):
                return "birthday"
            if suffix == "姓名":
                return "name"
    return None


def looks_like_grouped_headers(headers: List[str]) -> bool:
    hits = 0
    for h in headers:
        if "_" in h and resolve_grouped_field(h):
            hits += 1
    return hits >= 2


def field_key_for_label(conn: sqlite3.Connection, label: str, sample_values: List[Any]) -> str:
    row = conn.execute(
        "SELECT field_key FROM store_custom_field_defs WHERE entity='member' AND label=?",
        (label,),
    ).fetchone()
    if row:
        return row["field_key"]
    ftype = normalize_field_type(guess_value_type(label, sample_values))
    fkey = stable_field_key(label)
    conn.execute(
        """INSERT OR IGNORE INTO store_custom_field_defs (entity, field_key, label, field_type)
           VALUES ('member',?,?,?)""",
        (fkey, label, ftype),
    )
    return fkey


def row_to_member_payload(conn: sqlite3.Connection, row: Dict[str, str]) -> Dict[str, Any]:
    payload: Dict[str, Any] = {
        "name": None,
        "phone": "",
        "birthday": "",
        "due_date": "",
        "note": "",
        "tags": [],
        "fields": {},
    }
    for label, value in row.items():
        if is_blank(value):
            continue
        builtin = resolve_builtin(label) or resolve_grouped_field(label)
        if builtin == "name":
            payload["name"] = clean_text(value)
        elif builtin == "phone":
            payload["phone"] = normalize_phone(value) or clean_text(value)
        elif builtin == "birthday":
            payload["birthday"] = normalize_date(value) or clean_text(value)
        elif builtin == "due_date":
            payload["due_date"] = normalize_date(value) or clean_text(value)
        elif builtin == "tags":
            payload["tags"] = normalize_tags(value)
        elif builtin == "note":
            payload["note"] = normalize_optional_text(value) or ""
        else:
            fkey = field_key_for_label(conn, label, [value])
            payload["fields"][fkey] = clean_text(value)
    return payload
