#!/usr/bin/env python3
"""
库存管理脚本：支持多项目、自定义字段、CSV/XLSX 导入、出入库、库存查询、变动记录、导出。
数据存储在本地 SQLite，字段配置从用户上传的文件表头自动解析。
"""

import argparse
import csv
import io
import json
import os
import re
import sqlite3
import sys
import time
from datetime import datetime
from pathlib import Path

SCRIPT_DIR = Path(__file__).resolve().parent
WORKSPACE_DIR = Path.home() / ".openclaw" / "workspace" / "inventory-management"
DEFAULT_DB_PATH = WORKSPACE_DIR / "inventory.db"
DB_PATH = Path(os.environ.get("INVENTORY_DB_PATH", str(DEFAULT_DB_PATH)))

# ---------- 关键字段自动推断关键词 ----------

KEY_FIELD_HINTS = ["sku", "编码", "编号", "货号", "条码", "物料号", "id", "代码", "code"]
STOCK_FIELD_HINTS = ["库存", "数量", "stock", "qty", "quantity", "余量", "存量"]

# ---------- 数据库初始化 ----------


def get_db() -> sqlite3.Connection:
    DB_PATH.parent.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(str(DB_PATH))
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA foreign_keys=ON")
    _init_tables(conn)
    return conn


def _init_tables(conn: sqlite3.Connection) -> None:
    conn.executescript("""
        CREATE TABLE IF NOT EXISTS projects (
            id          INTEGER PRIMARY KEY AUTOINCREMENT,
            name        TEXT NOT NULL UNIQUE,
            field_config TEXT NOT NULL DEFAULT '[]',
            key_field   TEXT NOT NULL DEFAULT '',
            stock_field TEXT NOT NULL DEFAULT '',
            low_stock_threshold INTEGER NOT NULL DEFAULT 10,
            created_at  TEXT NOT NULL DEFAULT (datetime('now','localtime'))
        );
        CREATE TABLE IF NOT EXISTS products (
            id          INTEGER PRIMARY KEY AUTOINCREMENT,
            project_id  INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
            key_value   TEXT NOT NULL,
            stock_qty   REAL NOT NULL DEFAULT 0,
            data        TEXT NOT NULL DEFAULT '{}',
            status      TEXT NOT NULL DEFAULT 'active',
            created_at  TEXT NOT NULL DEFAULT (datetime('now','localtime')),
            updated_at  TEXT NOT NULL DEFAULT (datetime('now','localtime')),
            UNIQUE(project_id, key_value)
        );
        CREATE INDEX IF NOT EXISTS idx_products_project ON products(project_id, status);
        CREATE TABLE IF NOT EXISTS stock_logs (
            id          INTEGER PRIMARY KEY AUTOINCREMENT,
            project_id  INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
            key_value   TEXT NOT NULL,
            direction   TEXT NOT NULL CHECK(direction IN ('in','out')),
            type        TEXT NOT NULL DEFAULT '',
            quantity    REAL NOT NULL,
            before_qty  REAL NOT NULL,
            after_qty   REAL NOT NULL,
            remark      TEXT NOT NULL DEFAULT '',
            created_at  TEXT NOT NULL DEFAULT (datetime('now','localtime'))
        );
        CREATE INDEX IF NOT EXISTS idx_logs_project ON stock_logs(project_id, key_value);
        CREATE TABLE IF NOT EXISTS stocktakes (
            id          INTEGER PRIMARY KEY AUTOINCREMENT,
            project_id  INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
            status      TEXT NOT NULL DEFAULT 'pending',
            created_at  TEXT NOT NULL DEFAULT (datetime('now','localtime')),
            confirmed_at TEXT
        );
        CREATE TABLE IF NOT EXISTS stocktake_items (
            id            INTEGER PRIMARY KEY AUTOINCREMENT,
            stocktake_id  INTEGER NOT NULL REFERENCES stocktakes(id) ON DELETE CASCADE,
            key_value     TEXT NOT NULL,
            system_qty    REAL NOT NULL,
            actual_qty    REAL,
            diff          REAL
        );
    """)
    conn.commit()


# ---------- 文件解析 ----------


def _detect_csv_encoding(filepath: str) -> str:
    for enc in ("utf-8-sig", "utf-8", "gbk", "gb2312", "gb18030", "latin-1"):
        try:
            with open(filepath, "r", encoding=enc) as f:
                f.read(4096)
            return enc
        except (UnicodeDecodeError, UnicodeError):
            continue
    return "utf-8"


def parse_file(filepath: str) -> tuple[list[str], list[dict]]:
    """解析 CSV 或 XLSX 文件，返回 (表头列表, 数据行列表[dict])"""
    p = Path(filepath)
    if not p.is_file():
        raise FileNotFoundError(f"文件不存在: {filepath}")
    suffix = p.suffix.lower()
    if suffix == ".csv":
        return _parse_csv(filepath)
    elif suffix in (".xlsx", ".xls"):
        return _parse_xlsx(filepath)
    else:
        raise ValueError(f"不支持的文件格式: {suffix}，仅支持 .csv / .xlsx")


def _parse_csv(filepath: str) -> tuple[list[str], list[dict]]:
    enc = _detect_csv_encoding(filepath)
    with open(filepath, "r", encoding=enc, newline="") as f:
        reader = csv.DictReader(f)
        headers = reader.fieldnames or []
        headers = [h.strip() for h in headers if h and h.strip()]
        rows = []
        for row in reader:
            cleaned = {k.strip(): (v.strip() if isinstance(v, str) else v) for k, v in row.items() if k and k.strip()}
            rows.append(cleaned)
    return headers, rows


def _parse_xlsx(filepath: str) -> tuple[list[str], list[dict]]:
    try:
        from openpyxl import load_workbook
    except ImportError:
        raise ImportError("解析 XLSX 文件需要 openpyxl，请执行: pip install openpyxl")
    wb = load_workbook(filepath, read_only=True, data_only=True)
    ws = wb.active
    rows_iter = ws.iter_rows(values_only=True)
    header_row = next(rows_iter, None)
    if not header_row:
        raise ValueError("XLSX 文件为空或无表头")
    headers = [str(h).strip() for h in header_row if h is not None and str(h).strip()]
    data = []
    for row in rows_iter:
        if all(c is None for c in row):
            continue
        record = {}
        for i, h in enumerate(headers):
            val = row[i] if i < len(row) else None
            record[h] = str(val).strip() if val is not None else ""
        data.append(record)
    wb.close()
    return headers, data


# ---------- 字段推断 ----------


def _guess_field(headers: list[str], hints: list[str]) -> str | None:
    lower_headers = {h: h.lower() for h in headers}
    for h, lh in lower_headers.items():
        for hint in hints:
            if hint.lower() in lh:
                return h
    return None


def guess_key_field(headers: list[str]) -> str | None:
    return _guess_field(headers, KEY_FIELD_HINTS)


def guess_stock_field(headers: list[str]) -> str | None:
    return _guess_field(headers, STOCK_FIELD_HINTS)


def infer_field_type(values: list[str]) -> str:
    """从一列数据的样本推断类型: number / date / text"""
    samples = [v for v in values if v and v.strip()][:50]
    if not samples:
        return "text"
    num_count = 0
    date_count = 0
    date_re = re.compile(r"^\d{4}[-/]\d{1,2}[-/]\d{1,2}")
    for s in samples:
        s = s.strip()
        try:
            float(s.replace(",", ""))
            num_count += 1
            continue
        except ValueError:
            pass
        if date_re.match(s):
            date_count += 1
    if num_count > len(samples) * 0.7:
        return "number"
    if date_count > len(samples) * 0.7:
        return "date"
    return "text"


NUMBER_NAME_HINTS = ["数量", "库存", "价", "金额", "成本", "重量", "amount", "price", "cost", "qty", "stock", "weight", "count"]
DATE_NAME_HINTS = ["日期", "时间", "date", "time", "到期", "生产", "保质期"]


def infer_type_from_name(field_name: str) -> str:
    """仅根据字段名推断类型（用于自然语言建表，无数据样本时）。"""
    lower = field_name.lower()
    for hint in NUMBER_NAME_HINTS:
        if hint in lower:
            return "number"
    for hint in DATE_NAME_HINTS:
        if hint in lower:
            return "date"
    return "text"


def parse_fields_arg(fields_str: str) -> list[dict]:
    """解析 --fields 参数，支持两种格式：
    1. 简单格式: "SKU,名称,颜色,库存数量,售价" 或 "SKU:text,库存数量:number"
    2. JSON 格式: '[{"name":"SKU","type":"text"},...]'
    返回 [{"name":..., "type":...}, ...]
    """
    s = fields_str.strip()
    if s.startswith("["):
        try:
            items = json.loads(s)
        except json.JSONDecodeError as e:
            raise ValueError(
                f"--fields JSON 解析失败: {e}。"
                f"JSON 格式示例: '[{{\"name\":\"SKU\",\"type\":\"text\"}},{{\"name\":\"库存\",\"type\":\"number\"}}]'"
            )
        if not isinstance(items, list):
            raise ValueError("--fields JSON 必须是数组格式 [...]")
        result = []
        for i, item in enumerate(items):
            if isinstance(item, str):
                result.append({"name": item.strip(), "type": infer_type_from_name(item.strip())})
            elif isinstance(item, dict):
                name = item.get("name", "").strip()
                if not name:
                    raise ValueError(f"--fields JSON 第{i+1}项缺少 name 字段")
                ft = item.get("type", "").strip() or infer_type_from_name(name)
                if ft not in ("text", "number", "date"):
                    raise ValueError(f"字段「{name}」的 type「{ft}」无效，可选: text / number / date")
                result.append({"name": name, "type": ft})
            else:
                raise ValueError(f"--fields JSON 第{i+1}项格式不正确，应为对象 {{\"name\":...,\"type\":...}} 或字符串")
        return result

    parts = [p.strip() for p in s.split(",") if p.strip()]
    if not parts:
        raise ValueError("--fields 不能为空")
    result = []
    for part in parts:
        if ":" in part:
            name, ft = part.rsplit(":", 1)
            name = name.strip()
            ft = ft.strip().lower()
            if ft not in ("text", "number", "date"):
                raise ValueError(
                    f"字段「{name}」的类型「{ft}」无效，可选: text / number / date。"
                    f"示例: \"SKU:text,库存数量:number,生产日期:date\""
                )
        else:
            name = part.strip()
            ft = infer_type_from_name(name)
        if not name:
            continue
        result.append({"name": name, "type": ft})
    return result


# ---------- 项目辅助 ----------


def resolve_project(conn: sqlite3.Connection, project_name: str | None) -> sqlite3.Row:
    if project_name:
        row = conn.execute("SELECT * FROM projects WHERE name = ?", (project_name,)).fetchone()
        if not row:
            names = _list_project_names(conn)
            msg = f"项目「{project_name}」不存在"
            if names:
                msg += f"，已有项目: {names}"
            else:
                msg += "，当前无任何项目，请先用 init 命令创建"
            raise ValueError(msg)
        return row
    rows = conn.execute("SELECT * FROM projects").fetchall()
    if len(rows) == 0:
        raise ValueError(
            "尚无任何项目，请先用 init 命令创建项目。"
            "用法: init --project <项目名> --file <CSV或XLSX文件路径>"
        )
    if len(rows) == 1:
        return rows[0]
    names = [r["name"] for r in rows]
    raise ValueError(
        f"存在多个项目 {names}，请用 --project <项目名> 指定要操作的项目"
    )


def _get_field_config(project: sqlite3.Row) -> list[dict]:
    return json.loads(project["field_config"] or "[]")


# ---------- 终端表格打印 ----------


def _display_width(s: str) -> int:
    w = 0
    for c in s:
        w += 2 if "\u4e00" <= c <= "\u9fff" or "\u3000" <= c <= "\u303f" or "\uff00" <= c <= "\uffef" else 1
    return w


def _pad(s: str, width: int, align: str = "left") -> str:
    s = s or ""
    cur = _display_width(s)
    if cur >= width:
        return s
    pad = " " * (width - cur)
    return (s + pad) if align == "left" else (pad + s)


def print_table(headers: list[str], rows: list[list[str]], aligns: list[str] | None = None) -> None:
    if not headers:
        return
    if aligns is None:
        aligns = ["left"] * len(headers)
    col_widths = [max(_display_width(h) + 2, 6) for h in headers]
    for row in rows:
        for i, cell in enumerate(row):
            if i < len(col_widths):
                col_widths[i] = max(col_widths[i], _display_width(str(cell)) + 2)
    cap = 40
    col_widths = [min(w, cap) for w in col_widths]
    sep = " "
    print(sep.join(_pad(h, col_widths[i], aligns[i]) for i, h in enumerate(headers)))
    print(sep.join("-" * w for w in col_widths))
    for row in rows:
        cells = []
        for i in range(len(headers)):
            val = str(row[i]) if i < len(row) else ""
            if _display_width(val) > col_widths[i]:
                val = val[: col_widths[i] - 1] + "…"
            cells.append(_pad(val, col_widths[i], aligns[i] if i < len(aligns) else "left"))
        print(sep.join(cells))


def _ok(data: dict | None = None, **kwargs) -> None:
    out = {"ok": True}
    if data:
        out.update(data)
    out.update(kwargs)
    print(json.dumps(out, ensure_ascii=False, indent=2))


def _fail(error: str, *, usage: str | None = None, hint: str | None = None,
          valid_values: list | dict | None = None, example: str | None = None, **kwargs) -> None:
    """输出结构化错误信息，帮助调用方（LLM）快速定位问题并修正参数。
    - error: 错误描述
    - usage: 正确的命令用法示例
    - hint: 修复建议
    - valid_values: 合法取值范围（如项目列表、字段列表、商品标识列表）
    - example: 正确参数的完整示例
    """
    out: dict = {"ok": False, "error": error}
    if usage:
        out["usage"] = usage
    if hint:
        out["hint"] = hint
    if valid_values is not None:
        out["valid_values"] = valid_values
    if example:
        out["example"] = example
    out.update(kwargs)
    print(json.dumps(out, ensure_ascii=False))


# ---------- 校验辅助 ----------


def _list_project_names(conn: sqlite3.Connection) -> list[str]:
    return [r["name"] for r in conn.execute("SELECT name FROM projects ORDER BY name").fetchall()]


def _list_product_keys(conn: sqlite3.Connection, project_id: int, limit: int = 20) -> list[str]:
    rows = conn.execute(
        "SELECT key_value FROM products WHERE project_id = ? AND status = 'active' ORDER BY key_value LIMIT ?",
        (project_id, limit),
    ).fetchall()
    return [r["key_value"] for r in rows]


def _product_not_found(conn: sqlite3.Connection, proj: sqlite3.Row, key: str) -> None:
    """商品不存在时，输出详细错误：列出该项目已有的商品标识供参考。"""
    pid = proj["id"]
    keys = _list_product_keys(conn, pid)
    total = conn.execute(
        "SELECT COUNT(*) as c FROM products WHERE project_id = ? AND status = 'active'", (pid,)
    ).fetchone()["c"]
    suffix = f"（共 {total} 条，仅展示前 {len(keys)} 条）" if total > len(keys) else ""
    _fail(
        f"商品「{key}」在项目「{proj['name']}」中不存在",
        hint=f"请检查商品标识是否正确。该项目的唯一标识字段为「{proj['key_field']}」",
        valid_values={"existing_keys": keys, "note": suffix} if keys else None,
        usage=f"stock-query --project {proj['name']}  # 查看全部商品",
    )


def _validate_json_data(data: dict, proj: sqlite3.Row, purpose: str = "add") -> str | None:
    """校验 JSON 数据的字段是否与项目字段配置匹配。返回 None 表示通过，否则返回错误描述。"""
    fields = _get_field_config(proj)
    config_names = {f["name"] for f in fields}
    unknown = [k for k in data.keys() if k not in config_names]
    if unknown:
        return (f"JSON 中包含未知字段 {unknown}，"
                f"该项目可用字段为: {sorted(config_names)}")
    return None


def _validate_date(date_str: str, param_name: str) -> str | None:
    """校验日期格式 YYYY-MM-DD，返回 None 通过，否则返回错误描述。"""
    if not re.match(r"^\d{4}-\d{2}-\d{2}$", date_str):
        return f"参数 {param_name} 日期格式不正确:「{date_str}」，正确格式为 YYYY-MM-DD（如 2026-01-15）"
    try:
        datetime.strptime(date_str, "%Y-%m-%d")
    except ValueError:
        return f"参数 {param_name} 日期无效:「{date_str}」，请输入合法日期（如 2026-01-15）"
    return None


def _validate_filter(filter_str: str, proj: sqlite3.Row) -> str | None:
    """校验 --filter 格式和字段是否存在。"""
    if "=" not in filter_str:
        return (f"--filter 格式不正确:「{filter_str}」，正确格式为「字段名=值」（如 --filter 分类=配件）")
    fk, _ = filter_str.split("=", 1)
    fk = fk.strip()
    fields = _get_field_config(proj)
    config_names = [f["name"] for f in fields]
    if fk not in config_names:
        return f"--filter 中的字段名「{fk}」不存在，该项目可用字段为: {config_names}"
    return None


# ========== 命令实现 ==========

# ---------- create（自然语言建表） ----------


def cmd_create(args: argparse.Namespace) -> int:
    """通过直接指定字段来创建项目（无需上传文件）。适用于用户用自然语言描述表结构的场景。"""
    project_name = args.project
    fields_str = args.fields
    key_field = args.key_field
    stock_field = args.stock_field
    threshold = getattr(args, "low_stock_threshold", 10)

    if not project_name or not project_name.strip():
        _fail("--project 项目名称不能为空",
              usage='create --project <项目名> --fields "字段1,字段2,..." --key-field <标识字段> --stock-field <库存字段>',
              example='create --project 服装仓库 --fields "SKU,名称,颜色,尺码,库存数量,售价" --key-field SKU --stock-field 库存数量')
        return 1

    if not fields_str or not fields_str.strip():
        _fail("--fields 字段定义不能为空",
              hint="支持两种格式：\n"
                   "  1. 简单格式（逗号分隔）: \"SKU,名称,颜色,库存数量,售价\" 或 \"SKU:text,库存数量:number\"\n"
                   "  2. JSON 格式: '[{\"name\":\"SKU\",\"type\":\"text\"},{\"name\":\"库存数量\",\"type\":\"number\"}]'",
              example='create --project 服装仓库 --fields "SKU,名称,颜色,尺码,库存数量,售价" --key-field SKU --stock-field 库存数量')
        return 1

    try:
        field_list = parse_fields_arg(fields_str)
    except ValueError as e:
        _fail(str(e),
              hint="--fields 支持两种格式：\n"
                   "  1. 简单: \"SKU,名称,颜色,库存数量:number,售价:number\"\n"
                   "  2. JSON: '[{\"name\":\"SKU\",\"type\":\"text\"},...]'\n"
                   "  类型可选: text(默认) / number / date，不指定时根据字段名自动推断")
        return 1

    if len(field_list) < 2:
        _fail("至少需要 2 个字段（一个唯一标识 + 一个库存数量）",
              example='--fields "SKU,名称,库存数量,售价"')
        return 1

    field_names = [f["name"] for f in field_list]
    dup = [n for n in field_names if field_names.count(n) > 1]
    if dup:
        _fail(f"字段名重复: {list(set(dup))}，每个字段名必须唯一")
        return 1

    if not key_field:
        key_field = guess_key_field(field_names)
    if not stock_field:
        stock_field = guess_stock_field(field_names)

    guessed = []
    if key_field and not args.key_field:
        guessed.append(f"唯一标识字段 → {key_field}")
    if stock_field and not args.stock_field:
        guessed.append(f"库存数量字段 → {stock_field}")

    if not key_field:
        _fail("无法自动推断唯一标识字段，请用 --key-field 指定",
              hint="请从字段列表中选择一个作为商品唯一标识（如 SKU、编号）",
              valid_values=field_names,
              example=f'create --project {project_name} --fields "{fields_str}" --key-field {field_names[0]} --stock-field <库存字段>')
        return 1
    if not stock_field:
        _fail("无法自动推断库存数量字段，请用 --stock-field 指定",
              hint="请从字段列表中选择一个作为库存数量字段（值须为数字）",
              valid_values=field_names,
              example=f'create --project {project_name} --fields "{fields_str}" --key-field {key_field} --stock-field {field_names[-1]}')
        return 1
    if key_field not in field_names:
        _fail(f"--key-field「{key_field}」不在字段列表中",
              valid_values=field_names)
        return 1
    if stock_field not in field_names:
        _fail(f"--stock-field「{stock_field}」不在字段列表中",
              valid_values=field_names)
        return 1
    if key_field == stock_field:
        _fail(f"唯一标识字段和库存数量字段不能相同（都是「{key_field}」）",
              valid_values=field_names)
        return 1

    for f in field_list:
        if f["name"] == key_field:
            f["role"] = "key"
        elif f["name"] == stock_field:
            f["role"] = "stock"
            f["type"] = "number"

    conn = get_db()
    existing = conn.execute("SELECT id FROM projects WHERE name = ?", (project_name,)).fetchone()
    if existing:
        _fail(f"项目「{project_name}」已存在，不能重复创建",
              hint="若要向已有项目添加商品，请使用 product-add 命令",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1

    conn.execute(
        "INSERT INTO projects (name, field_config, key_field, stock_field, low_stock_threshold) VALUES (?,?,?,?,?)",
        (project_name, json.dumps(field_list, ensure_ascii=False), key_field, stock_field, threshold),
    )
    conn.commit()
    conn.close()

    print(f"项目「{project_name}」创建成功（空表，无初始数据）")
    if guessed:
        print("自动推断：" + "，".join(guessed))
    print(f"字段({len(field_list)}个):")
    for f in field_list:
        role = f.get("role", "")
        role_label = " ← 唯一标识" if role == "key" else (" ← 库存数量" if role == "stock" else "")
        print(f"  - {f['name']} ({f['type']}){role_label}")
    print(f"\n可通过以下方式添加商品：")
    print(f"  1. 手动添加: product-add --project {project_name} --data '<JSON>'")
    print(f"  2. 文件导入: import --project {project_name} --file <CSV/XLSX路径>")
    _ok(project=project_name, fields=[f["name"] for f in field_list],
        key_field=key_field, stock_field=stock_field, product_count=0)
    return 0


# ---------- init ----------


def cmd_init(args: argparse.Namespace) -> int:
    project_name = args.project
    filepath = args.file
    key_field = getattr(args, "key_field", None)
    stock_field = getattr(args, "stock_field", None)
    threshold = getattr(args, "low_stock_threshold", 10)

    if not project_name or not project_name.strip():
        _fail("--project 项目名称不能为空",
              usage="init --project <项目名> --file <文件路径>",
              example='init --project 原材料仓库 --file /path/to/data.csv')
        return 1

    if not filepath or not filepath.strip():
        _fail("--file 文件路径不能为空",
              usage="init --project <项目名> --file <CSV或XLSX文件路径>",
              example='init --project 原材料仓库 --file /path/to/data.csv')
        return 1

    p = Path(filepath)
    if not p.exists():
        _fail(f"文件不存在: {filepath}",
              hint="请检查文件路径是否正确，路径需为绝对路径或相对于当前工作目录的路径",
              usage="init --project <项目名> --file <CSV或XLSX文件路径>")
        return 1
    if p.suffix.lower() not in (".csv", ".xlsx", ".xls"):
        _fail(f"不支持的文件格式: {p.suffix}",
              hint="仅支持 .csv 和 .xlsx 格式",
              example="init --project 仓库A --file /path/to/data.csv")
        return 1

    try:
        headers, data = parse_file(filepath)
    except Exception as e:
        _fail(f"文件解析失败: {e}",
              hint="请确认文件格式正确且非空。CSV 文件第一行为表头，XLSX 需要 openpyxl（pip install openpyxl）")
        return 1

    if not headers:
        _fail("文件无有效表头（第一行为空或无可识别的列名）",
              hint="CSV/XLSX 文件的第一行必须为列名表头，如: SKU编码,商品名称,库存数量,...")
        return 1

    if len(data) == 0:
        _fail("文件有表头但无数据行",
              hint=f"检测到表头列: {headers}，但文件中没有数据行，请确认文件内容")
        return 1

    if not key_field:
        key_field = guess_key_field(headers)
    if not stock_field:
        stock_field = guess_stock_field(headers)

    guessed = []
    if key_field and getattr(args, "key_field", None) is None:
        guessed.append(f"唯一标识字段 → {key_field}")
    if stock_field and getattr(args, "stock_field", None) is None:
        guessed.append(f"库存数量字段 → {stock_field}")

    if not key_field:
        _fail("无法自动推断唯一标识字段（如 SKU/编号），请用 --key-field 指定",
              hint="请从以下列名中选择一个作为商品唯一标识",
              valid_values=headers,
              example=f'init --project {project_name} --file {filepath} --key-field {headers[0]} --stock-field <库存列名>')
        return 1
    if not stock_field:
        _fail("无法自动推断库存数量字段（如 库存/数量），请用 --stock-field 指定",
              hint="请从以下列名中选择一个作为库存数量字段（该字段的值须为数字）",
              valid_values=headers,
              example=f'init --project {project_name} --file {filepath} --key-field {key_field} --stock-field {headers[-1]}')
        return 1
    if key_field not in headers:
        _fail(f"指定的唯一标识字段「{key_field}」不在文件表头中",
              hint="--key-field 的值必须是文件表头中的某一列名",
              valid_values=headers)
        return 1
    if stock_field not in headers:
        _fail(f"指定的库存数量字段「{stock_field}」不在文件表头中",
              hint="--stock-field 的值必须是文件表头中的某一列名",
              valid_values=headers)
        return 1
    if key_field == stock_field:
        _fail(f"唯一标识字段和库存数量字段不能相同（都是「{key_field}」）",
              hint="--key-field 和 --stock-field 必须是不同的列",
              valid_values=headers)
        return 1

    col_values: dict[str, list[str]] = {h: [] for h in headers}
    for row in data:
        for h in headers:
            col_values[h].append(str(row.get(h, "")))

    field_config = []
    for h in headers:
        ft = infer_field_type(col_values[h])
        entry: dict = {"name": h, "type": ft}
        if h == key_field:
            entry["role"] = "key"
        elif h == stock_field:
            entry["role"] = "stock"
            entry["type"] = "number"
        field_config.append(entry)

    conn = get_db()
    existing = conn.execute("SELECT id FROM projects WHERE name = ?", (project_name,)).fetchone()
    if existing:
        _fail(f"项目「{project_name}」已存在，不能重复创建",
              hint="若要向该项目追加/更新数据，请使用 import 命令",
              usage=f'import --project {project_name} --file <新的CSV文件路径>',
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1

    conn.execute(
        "INSERT INTO projects (name, field_config, key_field, stock_field, low_stock_threshold) VALUES (?,?,?,?,?)",
        (project_name, json.dumps(field_config, ensure_ascii=False), key_field, stock_field, threshold),
    )
    conn.commit()
    proj = conn.execute("SELECT * FROM projects WHERE name = ?", (project_name,)).fetchone()
    pid = proj["id"]

    inserted = 0
    skipped = []
    for i, row in enumerate(data, start=2):
        kv = str(row.get(key_field, "")).strip()
        if not kv:
            skipped.append(f"第{i}行: 唯一标识为空")
            continue
        sq_raw = str(row.get(stock_field, "0")).strip().replace(",", "")
        try:
            sq = float(sq_raw) if sq_raw else 0
        except ValueError:
            sq = 0
        try:
            conn.execute(
                "INSERT INTO products (project_id, key_value, stock_qty, data) VALUES (?,?,?,?)",
                (pid, kv, sq, json.dumps(row, ensure_ascii=False)),
            )
            inserted += 1
        except sqlite3.IntegrityError:
            skipped.append(f"第{i}行: 标识「{kv}」重复")
    conn.commit()
    conn.close()

    print(f"项目「{project_name}」创建成功")
    if guessed:
        print("自动推断：" + "，".join(guessed))
    print(f"字段({len(field_config)}个): {', '.join(h for h in headers)}")
    print(f"导入: 成功 {inserted} 条" + (f"，跳过 {len(skipped)} 条" if skipped else ""))
    if skipped:
        for s in skipped[:10]:
            print(f"  - {s}")
    _ok(project=project_name, imported=inserted, skipped=len(skipped), fields=[f["name"] for f in field_config],
        key_field=key_field, stock_field=stock_field)
    return 0


# ---------- import ----------


def cmd_import(args: argparse.Namespace) -> int:
    if not getattr(args, "file", None) or not args.file.strip():
        _fail("--file 文件路径不能为空",
              usage="import --project <项目名> --file <CSV或XLSX文件路径>")
        return 1

    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="import --project <项目名> --file <文件路径>",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1

    p = Path(args.file)
    if not p.exists():
        _fail(f"文件不存在: {args.file}",
              hint="请检查文件路径是否正确")
        conn.close()
        return 1

    try:
        headers, data = parse_file(args.file)
    except Exception as e:
        _fail(f"文件解析失败: {e}")
        conn.close()
        return 1

    pid = proj["id"]
    key_field = proj["key_field"]
    stock_field = proj["stock_field"]
    config_fields = {f["name"] for f in _get_field_config(proj)}

    unknown = [h for h in headers if h not in config_fields]
    if unknown:
        _fail(f"文件中存在项目「{proj['name']}」未定义的字段: {unknown}",
              hint="导入文件的列名必须与项目已有字段一致（允许缺列，不允许多出新列）。"
                   "如需新增字段请先用 field-add 命令",
              valid_values={"project_fields": sorted(config_fields), "file_unknown_fields": unknown},
              usage=f"field-add --project {proj['name']} --name <新字段名> --type text|number|date")
        conn.close()
        return 1

    if key_field not in headers:
        _fail(f"文件缺少唯一标识字段「{key_field}」",
              hint=f"导入文件的表头中必须包含项目的唯一标识字段「{key_field}」",
              valid_values={"required_field": key_field, "file_headers": headers})
        conn.close()
        return 1

    inserted = 0
    updated = 0
    skipped = []
    for i, row in enumerate(data, start=2):
        kv = str(row.get(key_field, "")).strip()
        if not kv:
            skipped.append(f"第{i}行: 唯一标识为空")
            continue
        sq_raw = str(row.get(stock_field, "0")).strip().replace(",", "") if stock_field in row else None
        existing = conn.execute(
            "SELECT id, data FROM products WHERE project_id = ? AND key_value = ? AND status = 'active'",
            (pid, kv),
        ).fetchone()
        if existing:
            old_data = json.loads(existing["data"] or "{}")
            old_data.update(row)
            sq = float(sq_raw) if sq_raw else float(str(old_data.get(stock_field, 0)).replace(",", "") or 0)
            conn.execute(
                "UPDATE products SET data = ?, stock_qty = ?, updated_at = datetime('now','localtime') WHERE id = ?",
                (json.dumps(old_data, ensure_ascii=False), sq, existing["id"]),
            )
            updated += 1
        else:
            sq = float(sq_raw) if sq_raw else 0
            conn.execute(
                "INSERT INTO products (project_id, key_value, stock_qty, data) VALUES (?,?,?,?)",
                (pid, kv, sq, json.dumps(row, ensure_ascii=False)),
            )
            inserted += 1
    conn.commit()
    conn.close()
    print(f"导入完成: 新增 {inserted} 条，更新 {updated} 条" + (f"，跳过 {len(skipped)} 条" if skipped else ""))
    if skipped:
        for s in skipped[:10]:
            print(f"  - {s}")
    _ok(inserted=inserted, updated=updated, skipped=len(skipped))
    return 0


# ---------- project-list ----------


def cmd_project_list(args: argparse.Namespace) -> int:
    conn = get_db()
    projects = conn.execute("SELECT * FROM projects ORDER BY created_at").fetchall()
    if not projects:
        print("暂无项目，请先用 init 命令创建。")
        conn.close()
        return 0
    rows = []
    for p in projects:
        cnt = conn.execute(
            "SELECT COUNT(*) as c FROM products WHERE project_id = ? AND status = 'active'", (p["id"],)
        ).fetchone()["c"]
        fields = _get_field_config(p)
        rows.append([p["name"], str(cnt), str(len(fields)), p["key_field"], p["stock_field"], p["created_at"]])
    conn.close()
    print_table(["项目名称", "商品数", "字段数", "标识字段", "库存字段", "创建时间"], rows)
    return 0


# ---------- project-delete ----------


def cmd_project_delete(args: argparse.Namespace) -> int:
    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="project-delete --project <项目名>",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1
    pid = proj["id"]
    cnt = conn.execute(
        "SELECT COUNT(*) as c FROM products WHERE project_id = ? AND status = 'active'", (pid,)
    ).fetchone()["c"]
    conn.execute("DELETE FROM products WHERE project_id = ?", (pid,))
    conn.execute("DELETE FROM stock_logs WHERE project_id = ?", (pid,))
    conn.execute("DELETE FROM stocktake_items WHERE stocktake_id IN (SELECT id FROM stocktakes WHERE project_id = ?)", (pid,))
    conn.execute("DELETE FROM stocktakes WHERE project_id = ?", (pid,))
    conn.execute("DELETE FROM projects WHERE id = ?", (pid,))
    conn.commit()
    conn.close()
    print(f"项目「{proj['name']}」已删除（含 {cnt} 条商品及所有变动记录）")
    _ok(project=proj["name"], deleted_products=cnt)
    return 0


# ---------- field-list ----------


def cmd_field_list(args: argparse.Namespace) -> int:
    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="field-list --project <项目名>",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1
    conn.close()
    fields = _get_field_config(proj)
    rows = []
    for f in fields:
        role = f.get("role", "")
        role_zh = {"key": "唯一标识", "stock": "库存数量"}.get(role, "—")
        rows.append([f["name"], f.get("type", "text"), role_zh])
    print(f"项目「{proj['name']}」字段配置：")
    print_table(["字段名", "类型", "角色"], rows)
    return 0


# ---------- field-add ----------


def cmd_field_add(args: argparse.Namespace) -> int:
    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="field-add --project <项目名> --name <字段名> --type text|number|date",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1

    if not getattr(args, "name", None) or not args.name.strip():
        _fail("--name 字段名不能为空",
              usage="field-add --project <项目名> --name <字段名> --type text|number|date",
              example=f"field-add --project {proj['name']} --name 保质期 --type date")
        conn.close()
        return 1

    fields = _get_field_config(proj)
    existing_names = {f["name"] for f in fields}
    if args.name in existing_names:
        _fail(f"字段「{args.name}」在项目「{proj['name']}」中已存在",
              valid_values={"existing_fields": sorted(existing_names)})
        conn.close()
        return 1
    fields.append({"name": args.name, "type": args.type or "text"})
    conn.execute("UPDATE projects SET field_config = ? WHERE id = ?",
                 (json.dumps(fields, ensure_ascii=False), proj["id"]))
    conn.commit()
    conn.close()
    print(f"已为项目「{proj['name']}」新增字段「{args.name}」(类型: {args.type or 'text'})")
    _ok(field=args.name, type=args.type or "text")
    return 0


# ---------- field-delete ----------


def cmd_field_delete(args: argparse.Namespace) -> int:
    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="field-delete --project <项目名> --name <字段名>",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1

    if not getattr(args, "name", None) or not args.name.strip():
        fields = _get_field_config(proj)
        _fail("--name 字段名不能为空",
              hint="请指定要删除的字段名",
              valid_values={"deletable_fields": [
                  f["name"] for f in fields if f.get("role") not in ("key", "stock")
              ]},
              usage=f"field-delete --project {proj['name']} --name <字段名>")
        conn.close()
        return 1

    fields = _get_field_config(proj)
    field_names = [f["name"] for f in fields]
    deletable = [f["name"] for f in fields if f.get("role") not in ("key", "stock")]

    to_delete = [n.strip() for n in args.name.split(",") if n.strip()]
    if not to_delete:
        _fail("--name 解析后为空，请提供要删除的字段名",
              valid_values={"deletable_fields": deletable})
        conn.close()
        return 1

    blocked = []
    not_found = []
    will_delete = []
    for name in to_delete:
        match = next((f for f in fields if f["name"] == name), None)
        if not match:
            not_found.append(name)
        elif match.get("role") in ("key", "stock"):
            blocked.append(name)
        else:
            will_delete.append(name)

    if not_found:
        _fail(f"以下字段在项目「{proj['name']}」中不存在: {not_found}",
              hint="请检查字段名是否正确",
              valid_values={"existing_fields": field_names, "deletable_fields": deletable})
        conn.close()
        return 1
    if blocked:
        key_f = proj["key_field"]
        stock_f = proj["stock_field"]
        _fail(f"以下字段是核心字段，不能删除: {blocked}（唯一标识:「{key_f}」，库存数量:「{stock_f}」）",
              hint="唯一标识字段和库存数量字段是项目正常运行的基础，不可删除",
              valid_values={"deletable_fields": deletable})
        conn.close()
        return 1
    if not will_delete:
        _fail("没有可删除的字段",
              valid_values={"deletable_fields": deletable})
        conn.close()
        return 1

    new_fields = [f for f in fields if f["name"] not in will_delete]
    conn.execute("UPDATE projects SET field_config = ? WHERE id = ?",
                 (json.dumps(new_fields, ensure_ascii=False), proj["id"]))

    pid = proj["id"]
    products = conn.execute(
        "SELECT id, data FROM products WHERE project_id = ? AND status = 'active'", (pid,)
    ).fetchall()
    for p in products:
        data = json.loads(p["data"] or "{}")
        changed = False
        for name in will_delete:
            if name in data:
                del data[name]
                changed = True
        if changed:
            conn.execute("UPDATE products SET data = ?, updated_at = datetime('now','localtime') WHERE id = ?",
                         (json.dumps(data, ensure_ascii=False), p["id"]))
    conn.commit()
    conn.close()

    remaining = [f["name"] for f in new_fields]
    print(f"已从项目「{proj['name']}」删除字段: {will_delete}")
    print(f"剩余字段({len(remaining)}个): {remaining}")
    _ok(deleted_fields=will_delete, remaining_fields=remaining, affected_products=len(products))
    return 0


# ---------- product-add ----------


def cmd_product_add(args: argparse.Namespace) -> int:
    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="product-add --project <项目名> --data '<JSON>'",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1

    if not getattr(args, "data", None) or not args.data.strip():
        fields = _get_field_config(proj)
        field_names = [f["name"] for f in fields]
        example_data = {fn: "<值>" for fn in field_names}
        _fail("--data 参数不能为空，需传入 JSON 格式的商品数据",
              hint=f"该项目的字段为: {field_names}",
              example=f'product-add --project {proj["name"]} --data \'{json.dumps(example_data, ensure_ascii=False)}\'')
        conn.close()
        return 1

    try:
        data = json.loads(args.data)
    except json.JSONDecodeError as e:
        fields = _get_field_config(proj)
        field_names = [f["name"] for f in fields]
        example_data = {fn: "<值>" for fn in field_names}
        _fail(f"--data JSON 解析失败: {e}",
              hint="--data 的值必须是合法的 JSON 字符串，注意使用英文双引号",
              example=f'--data \'{json.dumps(example_data, ensure_ascii=False)}\'')
        conn.close()
        return 1

    if not isinstance(data, dict):
        _fail("--data 必须是 JSON 对象（字典），不能是数组或其他类型",
              example='--data \'{"SKU":"BT-003","商品名":"蓝牙音箱","库存":0}\'')
        conn.close()
        return 1

    field_err = _validate_json_data(data, proj, purpose="add")
    if field_err:
        fields = _get_field_config(proj)
        field_names = [f["name"] for f in fields]
        _fail(field_err,
              hint="--data 中的 key 必须是项目已定义的字段名",
              valid_values={"project_fields": field_names})
        conn.close()
        return 1

    key_field = proj["key_field"]
    stock_field = proj["stock_field"]
    kv = str(data.get(key_field, "")).strip()
    if not kv:
        fields = _get_field_config(proj)
        field_names = [f["name"] for f in fields]
        _fail(f"JSON 数据中缺少唯一标识字段「{key_field}」或其值为空",
              hint=f"唯一标识字段「{key_field}」为必填，不能为空",
              example=f'--data \'{{"{ key_field}":"XX-001",...}}\'',
              valid_values={"key_field": key_field, "all_fields": field_names})
        conn.close()
        return 1

    sq_raw = str(data.get(stock_field, "0")).strip().replace(",", "")
    try:
        sq = float(sq_raw) if sq_raw else 0
    except ValueError:
        _fail(f"库存字段「{stock_field}」的值「{data.get(stock_field)}」不是有效数字",
              hint=f"「{stock_field}」字段值必须为数字（如 0、100、50.5）")
        conn.close()
        return 1

    try:
        conn.execute(
            "INSERT INTO products (project_id, key_value, stock_qty, data) VALUES (?,?,?,?)",
            (proj["id"], kv, sq, json.dumps(data, ensure_ascii=False)),
        )
        conn.commit()
    except sqlite3.IntegrityError:
        _fail(f"商品「{kv}」在项目「{proj['name']}」中已存在，不能重复添加",
              hint="若要更新已有商品，请使用 product-edit 命令",
              usage=f'product-edit --project {proj["name"]} --key {kv} --set \'{{...}}\'')
        conn.close()
        return 1
    conn.close()
    print(f"商品「{kv}」添加成功，库存: {sq}")
    _ok(key=kv, stock=sq)
    return 0


# ---------- product-edit ----------


def cmd_product_edit(args: argparse.Namespace) -> int:
    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="product-edit --project <项目名> --key <商品标识> --set '<JSON>'",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1

    if not getattr(args, "key", None) or not args.key.strip():
        _fail("--key 参数不能为空",
              hint=f"请传入商品的唯一标识值（字段名:「{proj['key_field']}」）",
              usage=f"product-edit --project {proj['name']} --key <标识值> --set '<JSON>'")
        conn.close()
        return 1

    if not getattr(args, "set", None) or not args.set.strip():
        fields = _get_field_config(proj)
        field_names = [f["name"] for f in fields]
        _fail("--set 参数不能为空，需传入要更新的字段 JSON",
              hint=f"该项目可更新的字段: {field_names}",
              example=f'product-edit --project {proj["name"]} --key {args.key} --set \'{{"售价":299}}\'')
        conn.close()
        return 1

    try:
        updates = json.loads(args.set)
    except json.JSONDecodeError as e:
        fields = _get_field_config(proj)
        field_names = [f["name"] for f in fields]
        _fail(f"--set JSON 解析失败: {e}",
              hint="--set 的值必须是合法 JSON 对象，只需包含要修改的字段",
              example=f'--set \'{{"售价":259,"商品名":"新名称"}}\'',
              valid_values={"project_fields": field_names})
        conn.close()
        return 1

    if not isinstance(updates, dict):
        _fail("--set 必须是 JSON 对象（字典），不能是数组或其他类型",
              example='--set \'{"售价":259}\'')
        conn.close()
        return 1

    if not updates:
        _fail("--set JSON 对象为空，没有需要更新的字段",
              example='--set \'{"售价":259}\'')
        conn.close()
        return 1

    field_err = _validate_json_data(updates, proj, purpose="edit")
    if field_err:
        fields = _get_field_config(proj)
        field_names = [f["name"] for f in fields]
        _fail(field_err,
              hint="--set 中的 key 必须是项目已定义的字段名",
              valid_values={"project_fields": field_names})
        conn.close()
        return 1

    pid = proj["id"]
    row = conn.execute(
        "SELECT * FROM products WHERE project_id = ? AND key_value = ? AND status = 'active'",
        (pid, args.key),
    ).fetchone()
    if not row:
        _product_not_found(conn, proj, args.key)
        conn.close()
        return 1

    old_data = json.loads(row["data"] or "{}")
    old_data.update(updates)

    stock_field = proj["stock_field"]
    sq = row["stock_qty"]
    if stock_field in updates:
        raw = str(updates[stock_field]).strip().replace(",", "")
        try:
            sq = float(raw)
        except ValueError:
            _fail(f"库存字段「{stock_field}」的新值「{updates[stock_field]}」不是有效数字",
                  hint=f"通过 --set 修改「{stock_field}」时，值必须为数字")
            conn.close()
            return 1

    key_field = proj["key_field"]
    new_kv = str(old_data.get(key_field, args.key)).strip()

    conn.execute(
        "UPDATE products SET key_value = ?, stock_qty = ?, data = ?, updated_at = datetime('now','localtime') WHERE id = ?",
        (new_kv, sq, json.dumps(old_data, ensure_ascii=False), row["id"]),
    )
    conn.commit()
    conn.close()
    print(f"商品「{args.key}」更新成功")
    _ok(key=new_kv, updated_fields=list(updates.keys()))
    return 0


# ---------- product-delete ----------


def cmd_product_delete(args: argparse.Namespace) -> int:
    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="product-delete --project <项目名> --key <商品标识>",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1

    if not getattr(args, "key", None) or not args.key.strip():
        _fail("--key 参数不能为空",
              hint=f"请传入要删除商品的唯一标识值（字段名:「{proj['key_field']}」）",
              valid_values={"existing_keys": _list_product_keys(conn, proj["id"])})
        conn.close()
        return 1

    pid = proj["id"]
    row = conn.execute(
        "SELECT * FROM products WHERE project_id = ? AND key_value = ? AND status = 'active'",
        (pid, args.key),
    ).fetchone()
    if not row:
        _product_not_found(conn, proj, args.key)
        conn.close()
        return 1
    conn.execute(
        "UPDATE products SET status = 'deleted', updated_at = datetime('now','localtime') WHERE id = ?",
        (row["id"],),
    )
    conn.commit()
    conn.close()
    print(f"商品「{args.key}」已删除（软删除）")
    _ok(key=args.key)
    return 0


# ---------- product-list ----------


def cmd_product_list(args: argparse.Namespace) -> int:
    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="product-list --project <项目名> [--search <关键词>] [--filter 字段名=值]",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1
    pid = proj["id"]
    fields = _get_field_config(proj)
    field_names = [f["name"] for f in fields]

    filter_str = getattr(args, "filter", None)
    if filter_str:
        filter_err = _validate_filter(filter_str, proj)
        if filter_err:
            _fail(filter_err, valid_values={"project_fields": field_names})
            conn.close()
            return 1

    query = "SELECT * FROM products WHERE project_id = ? AND status = 'active'"
    params: list = [pid]

    rows = conn.execute(query, params).fetchall()
    conn.close()

    search = getattr(args, "search", None)

    result_rows = []
    for r in rows:
        data = json.loads(r["data"] or "{}")
        if search:
            matched = any(search.lower() in str(v).lower() for v in data.values())
            if not matched:
                continue
        if filter_str and "=" in filter_str:
            fk, fv = filter_str.split("=", 1)
            if str(data.get(fk.strip(), "")).strip() != fv.strip():
                continue
        row_cells = [str(data.get(fn, "")) for fn in field_names]
        result_rows.append(row_cells)

    if not result_rows:
        print("无匹配商品")
        return 0
    print(f"项目「{proj['name']}」商品列表 ({len(result_rows)} 条)：")
    print_table(field_names, result_rows)
    return 0


# ---------- product-detail ----------


def cmd_product_detail(args: argparse.Namespace) -> int:
    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="product-detail --project <项目名> --key <商品标识>",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1

    if not getattr(args, "key", None) or not args.key.strip():
        _fail("--key 参数不能为空",
              hint=f"请传入商品的唯一标识值（字段名:「{proj['key_field']}」）",
              valid_values={"existing_keys": _list_product_keys(conn, proj["id"])})
        conn.close()
        return 1

    pid = proj["id"]
    row = conn.execute(
        "SELECT * FROM products WHERE project_id = ? AND key_value = ? AND status = 'active'",
        (pid, args.key),
    ).fetchone()
    if not row:
        _product_not_found(conn, proj, args.key)
        conn.close()
        return 1

    data = json.loads(row["data"] or "{}")
    fields = _get_field_config(proj)
    print(f"---------- 商品详情 ----------")
    for f in fields:
        fn = f["name"]
        val = data.get(fn, "")
        role = f.get("role", "")
        suffix = " ← 唯一标识" if role == "key" else (" ← 库存数量" if role == "stock" else "")
        print(f"  {fn}: {val}{suffix}")
    print(f"  [系统库存]: {row['stock_qty']}")
    print(f"  [状态]: {row['status']}")
    print(f"  [创建时间]: {row['created_at']}")
    print(f"  [更新时间]: {row['updated_at']}")

    logs = conn.execute(
        "SELECT * FROM stock_logs WHERE project_id = ? AND key_value = ? ORDER BY created_at DESC LIMIT 10",
        (pid, args.key),
    ).fetchall()
    conn.close()
    if logs:
        print(f"\n  最近 {len(logs)} 条变动记录：")
        for lg in logs:
            d = "入库" if lg["direction"] == "in" else "出库"
            print(f"    {lg['created_at']}  {d}({lg['type']})  数量:{lg['quantity']}  {lg['before_qty']}→{lg['after_qty']}  {lg['remark']}")
    print(f"------------------------------")
    return 0


# ---------- stock-in ----------


def cmd_stock_in(args: argparse.Namespace) -> int:
    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="stock-in --project <项目名> --key <商品标识> --quantity <数量>",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1

    if not getattr(args, "key", None) or not args.key.strip():
        _fail("--key 参数不能为空",
              hint=f"请传入商品的唯一标识值（字段名:「{proj['key_field']}」）",
              valid_values={"existing_keys": _list_product_keys(conn, proj["id"])},
              usage=f"stock-in --project {proj['name']} --key <标识值> --quantity <数量>")
        conn.close()
        return 1

    pid = proj["id"]
    row = conn.execute(
        "SELECT * FROM products WHERE project_id = ? AND key_value = ? AND status = 'active'",
        (pid, args.key),
    ).fetchone()
    if not row:
        _product_not_found(conn, proj, args.key)
        conn.close()
        return 1
    qty = float(args.quantity)
    if qty <= 0:
        _fail("入库数量必须为正数（大于0）",
              hint=f"当前传入的 --quantity 为 {args.quantity}，请传入正数",
              example=f"stock-in --key {args.key} --quantity 100")
        conn.close()
        return 1
    before = row["stock_qty"]
    after = before + qty

    stock_field = proj["stock_field"]
    data = json.loads(row["data"] or "{}")
    data[stock_field] = after

    conn.execute(
        "UPDATE products SET stock_qty = ?, data = ?, updated_at = datetime('now','localtime') WHERE id = ?",
        (after, json.dumps(data, ensure_ascii=False), row["id"]),
    )
    conn.execute(
        "INSERT INTO stock_logs (project_id, key_value, direction, type, quantity, before_qty, after_qty, remark) VALUES (?,?,?,?,?,?,?,?)",
        (pid, args.key, "in", args.type or "purchase", qty, before, after, args.remark or ""),
    )
    conn.commit()
    conn.close()
    print(f"入库成功：商品「{args.key}」库存 {before} → {after}（+{qty}）")
    _ok(key=args.key, before=before, after=after, quantity=qty)
    return 0


# ---------- stock-out ----------


def cmd_stock_out(args: argparse.Namespace) -> int:
    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="stock-out --project <项目名> --key <商品标识> --quantity <数量>",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1

    if not getattr(args, "key", None) or not args.key.strip():
        _fail("--key 参数不能为空",
              hint=f"请传入商品的唯一标识值（字段名:「{proj['key_field']}」）",
              valid_values={"existing_keys": _list_product_keys(conn, proj["id"])},
              usage=f"stock-out --project {proj['name']} --key <标识值> --quantity <数量>")
        conn.close()
        return 1

    pid = proj["id"]
    row = conn.execute(
        "SELECT * FROM products WHERE project_id = ? AND key_value = ? AND status = 'active'",
        (pid, args.key),
    ).fetchone()
    if not row:
        _product_not_found(conn, proj, args.key)
        conn.close()
        return 1
    qty = float(args.quantity)
    if qty <= 0:
        _fail("出库数量必须为正数（大于0）",
              hint=f"当前传入的 --quantity 为 {args.quantity}，请传入正数",
              example=f"stock-out --key {args.key} --quantity 5")
        conn.close()
        return 1
    before = row["stock_qty"]
    if qty > before:
        _fail(f"库存不足：商品「{args.key}」当前库存为 {before}，请求出库 {qty}",
              hint=f"出库数量不能超过当前库存 {before}，请减少出库数量或先入库补货",
              current_stock=before, requested=qty)
        conn.close()
        return 1
    after = before - qty

    stock_field = proj["stock_field"]
    data = json.loads(row["data"] or "{}")
    data[stock_field] = after

    conn.execute(
        "UPDATE products SET stock_qty = ?, data = ?, updated_at = datetime('now','localtime') WHERE id = ?",
        (after, json.dumps(data, ensure_ascii=False), row["id"]),
    )
    conn.execute(
        "INSERT INTO stock_logs (project_id, key_value, direction, type, quantity, before_qty, after_qty, remark) VALUES (?,?,?,?,?,?,?,?)",
        (pid, args.key, "out", args.type or "sale", qty, before, after, args.remark or ""),
    )
    conn.commit()
    conn.close()
    print(f"出库成功：商品「{args.key}」库存 {before} → {after}（-{qty}）")
    _ok(key=args.key, before=before, after=after, quantity=qty)
    return 0


# ---------- stock-query ----------


def cmd_stock_query(args: argparse.Namespace) -> int:
    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="stock-query --project <项目名> [--key <商品标识>] [--low-stock] [--filter 字段名=值]",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1
    pid = proj["id"]
    fields = _get_field_config(proj)
    field_names = [f["name"] for f in fields]
    threshold = proj["low_stock_threshold"]

    filter_str = getattr(args, "filter", None)
    if filter_str:
        filter_err = _validate_filter(filter_str, proj)
        if filter_err:
            _fail(filter_err, valid_values={"project_fields": field_names})
            conn.close()
            return 1

    if getattr(args, "key", None):
        row = conn.execute(
            "SELECT * FROM products WHERE project_id = ? AND key_value = ? AND status = 'active'",
            (pid, args.key),
        ).fetchone()
        if not row:
            _product_not_found(conn, proj, args.key)
            conn.close()
            return 1
        data = json.loads(row["data"] or "{}")
        alert = "⚠ 低库存" if row["stock_qty"] <= threshold else ""
        print(f"商品「{args.key}」库存: {row['stock_qty']} {alert}")
        for fn in field_names:
            print(f"  {fn}: {data.get(fn, '')}")
        return 0

    rows = conn.execute(
        "SELECT * FROM products WHERE project_id = ? AND status = 'active' ORDER BY stock_qty ASC",
        (pid,),
    ).fetchall()
    conn.close()

    low_stock = getattr(args, "low_stock", False)
    filter_str = getattr(args, "filter", None)

    display_fields = [proj["key_field"], proj["stock_field"]]
    for fn in field_names:
        if fn not in display_fields:
            display_fields.append(fn)
    display_fields.append("预警")

    result_rows = []
    for r in rows:
        data = json.loads(r["data"] or "{}")
        if low_stock and r["stock_qty"] > threshold:
            continue
        if filter_str and "=" in filter_str:
            fk, fv = filter_str.split("=", 1)
            if str(data.get(fk.strip(), "")).strip() != fv.strip():
                continue
        cells = []
        for fn in display_fields[:-1]:
            cells.append(str(data.get(fn, "")))
        cells.append("⚠" if r["stock_qty"] <= threshold else "")
        result_rows.append(cells)

    if not result_rows:
        print("无匹配商品" + ("（低库存预警）" if low_stock else ""))
        return 0
    title = "低库存预警" if low_stock else "库存查询"
    print(f"项目「{proj['name']}」{title} ({len(result_rows)} 条)：")
    print_table(display_fields, result_rows)
    return 0


# ---------- stock-log ----------


def cmd_stock_log(args: argparse.Namespace) -> int:
    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="stock-log --project <项目名> [--key <标识>] [--direction in|out] [--from YYYY-MM-DD] [--to YYYY-MM-DD]",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1
    pid = proj["id"]

    if getattr(args, "from_date", None):
        date_err = _validate_date(args.from_date, "--from")
        if date_err:
            _fail(date_err)
            conn.close()
            return 1
    if getattr(args, "to_date", None):
        date_err = _validate_date(args.to_date, "--to")
        if date_err:
            _fail(date_err)
            conn.close()
            return 1

    query = "SELECT * FROM stock_logs WHERE project_id = ?"
    params: list = [pid]

    if getattr(args, "key", None):
        query += " AND key_value = ?"
        params.append(args.key)
    if getattr(args, "direction", None):
        query += " AND direction = ?"
        params.append(args.direction)
    if getattr(args, "from_date", None):
        query += " AND created_at >= ?"
        params.append(args.from_date)
    if getattr(args, "to_date", None):
        query += " AND created_at <= ?"
        params.append(args.to_date + " 23:59:59")

    query += " ORDER BY created_at DESC LIMIT 100"
    logs = conn.execute(query, params).fetchall()
    conn.close()

    if not logs:
        print("无变动记录")
        return 0

    TYPE_ZH = {
        "purchase": "采购入库", "return": "退货", "other": "其他",
        "sale": "销售出库", "damage": "报损",
    }
    headers = ["时间", "商品标识", "方向", "类型", "数量", "变动前", "变动后", "备注"]
    rows = []
    for lg in logs:
        d = "入库" if lg["direction"] == "in" else "出库"
        t = TYPE_ZH.get(lg["type"], lg["type"])
        rows.append([
            lg["created_at"], lg["key_value"], d, t,
            str(lg["quantity"]), str(lg["before_qty"]), str(lg["after_qty"]), lg["remark"],
        ])
    print(f"变动记录 ({len(rows)} 条)：")
    print_table(headers, rows)
    return 0


# ---------- export ----------


def cmd_export(args: argparse.Namespace) -> int:
    conn = get_db()
    try:
        proj = resolve_project(conn, args.project)
    except ValueError as e:
        _fail(str(e), usage="export --project <项目名> --type products|logs [--output <文件路径>]",
              valid_values={"existing_projects": _list_project_names(conn)})
        conn.close()
        return 1
    pid = proj["id"]
    export_type = args.type or "products"
    ts = datetime.now().strftime("%Y%m%d_%H%M%S")
    default_name = f"export_{proj['name']}_{export_type}_{ts}.csv"
    output = args.output or str(WORKSPACE_DIR / default_name)

    if export_type == "products":
        fields = _get_field_config(proj)
        field_names = [f["name"] for f in fields]
        rows = conn.execute(
            "SELECT * FROM products WHERE project_id = ? AND status = 'active'", (pid,)
        ).fetchall()
        conn.close()
        with open(output, "w", encoding="utf-8-sig", newline="") as f:
            writer = csv.DictWriter(f, fieldnames=field_names)
            writer.writeheader()
            for r in rows:
                data = json.loads(r["data"] or "{}")
                writer.writerow({fn: data.get(fn, "") for fn in field_names})
        print(f"已导出 {len(rows)} 条商品数据 → {output}")
    elif export_type == "logs":
        logs = conn.execute(
            "SELECT * FROM stock_logs WHERE project_id = ? ORDER BY created_at DESC", (pid,)
        ).fetchall()
        conn.close()
        log_fields = ["created_at", "key_value", "direction", "type", "quantity", "before_qty", "after_qty", "remark"]
        with open(output, "w", encoding="utf-8-sig", newline="") as f:
            writer = csv.DictWriter(f, fieldnames=log_fields)
            writer.writeheader()
            for lg in logs:
                writer.writerow({k: lg[k] for k in log_fields})
        print(f"已导出 {len(logs)} 条变动记录 → {output}")
    else:
        _fail(f"不支持的导出类型: {export_type}，可选 products / logs")
        conn.close()
        return 1
    _ok(output=output, type=export_type)
    return 0


# ========== CLI 入口 ==========


def main() -> int:
    parser = argparse.ArgumentParser(description="库存管理工具（多项目、自定义字段）")
    sub = parser.add_subparsers(dest="command", required=True)

    # create（自然语言建表）
    p = sub.add_parser("create", help="通过指定字段名直接创建空项目（无需上传文件，用户用自然语言描述字段时使用）")
    p.add_argument("--project", required=True, help="项目名称")
    p.add_argument("--fields", required=True,
                   help='字段定义。简单格式: "SKU,名称,颜色,库存数量,售价" 或带类型: "SKU:text,库存数量:number"；'
                        'JSON 格式: \'[{"name":"SKU","type":"text"},...]\'。类型可选 text/number/date，不指定时自动推断')
    p.add_argument("--key-field", default=None, help="唯一标识字段名（不传则自动推断）")
    p.add_argument("--stock-field", default=None, help="库存数量字段名（不传则自动推断）")
    p.add_argument("--low-stock-threshold", type=int, default=10, help="低库存预警阈值（默认10）")
    p.set_defaults(func=cmd_create)

    # init（从文件创建）
    p = sub.add_parser("init", help="从 CSV/XLSX 文件创建项目：解析表头创建项目并导入数据")
    p.add_argument("--project", required=True, help="项目名称")
    p.add_argument("--file", required=True, help="CSV 或 XLSX 文件路径")
    p.add_argument("--key-field", default=None, help="唯一标识字段名（不传则自动推断）")
    p.add_argument("--stock-field", default=None, help="库存数量字段名（不传则自动推断）")
    p.add_argument("--low-stock-threshold", type=int, default=10, help="低库存预警阈值（默认10）")
    p.set_defaults(func=cmd_init)

    # import
    p = sub.add_parser("import", help="追加/更新导入数据到已有项目")
    p.add_argument("--project", default=None, help="项目名称（单项目可省略）")
    p.add_argument("--file", required=True, help="CSV 或 XLSX 文件路径")
    p.set_defaults(func=cmd_import)

    # project-list
    p = sub.add_parser("project-list", help="查看所有项目")
    p.set_defaults(func=cmd_project_list)

    # project-delete
    p = sub.add_parser("project-delete", help="删除项目及其所有数据")
    p.add_argument("--project", required=True, help="项目名称")
    p.set_defaults(func=cmd_project_delete)

    # field-list
    p = sub.add_parser("field-list", help="查看项目字段配置")
    p.add_argument("--project", default=None, help="项目名称（单项目可省略）")
    p.set_defaults(func=cmd_field_list)

    # field-add
    p = sub.add_parser("field-add", help="为项目新增自定义字段")
    p.add_argument("--project", default=None, help="项目名称（单项目可省略）")
    p.add_argument("--name", required=True, help="字段名")
    p.add_argument("--type", default="text", choices=["text", "number", "date"], help="字段类型")
    p.set_defaults(func=cmd_field_add)

    # field-delete
    p = sub.add_parser("field-delete", help="删除字段（支持逗号分隔批量删除，唯一标识和库存字段不可删）")
    p.add_argument("--project", default=None, help="项目名称（单项目可省略）")
    p.add_argument("--name", required=True, help="要删除的字段名（多个用逗号分隔，如 \"条码,保质期,进价\"）")
    p.set_defaults(func=cmd_field_delete)

    # product-add
    p = sub.add_parser("product-add", help="添加单个商品")
    p.add_argument("--project", default=None, help="项目名称（单项目可省略）")
    p.add_argument("--data", required=True, help="商品数据 JSON 字符串")
    p.set_defaults(func=cmd_product_add)

    # product-edit
    p = sub.add_parser("product-edit", help="编辑商品字段")
    p.add_argument("--project", default=None, help="项目名称（单项目可省略）")
    p.add_argument("--key", required=True, help="商品唯一标识值")
    p.add_argument("--set", required=True, help="要更新的字段 JSON 字符串")
    p.set_defaults(func=cmd_product_edit)

    # product-delete
    p = sub.add_parser("product-delete", help="删除商品（软删除）")
    p.add_argument("--project", default=None, help="项目名称（单项目可省略）")
    p.add_argument("--key", required=True, help="商品唯一标识值")
    p.set_defaults(func=cmd_product_delete)

    # product-list
    p = sub.add_parser("product-list", help="查询商品列表")
    p.add_argument("--project", default=None, help="项目名称（单项目可省略）")
    p.add_argument("--search", default=None, help="模糊搜索关键词")
    p.add_argument("--filter", default=None, help="精确筛选 字段名=值")
    p.set_defaults(func=cmd_product_list)

    # product-detail
    p = sub.add_parser("product-detail", help="查看商品详情")
    p.add_argument("--project", default=None, help="项目名称（单项目可省略）")
    p.add_argument("--key", required=True, help="商品唯一标识值")
    p.set_defaults(func=cmd_product_detail)

    # stock-in
    p = sub.add_parser("stock-in", help="入库")
    p.add_argument("--project", default=None, help="项目名称（单项目可省略）")
    p.add_argument("--key", required=True, help="商品唯一标识值")
    p.add_argument("--quantity", required=True, type=float, help="入库数量")
    p.add_argument("--type", default="purchase", choices=["purchase", "return", "other"], help="入库类型")
    p.add_argument("--remark", default="", help="备注")
    p.set_defaults(func=cmd_stock_in)

    # stock-out
    p = sub.add_parser("stock-out", help="出库")
    p.add_argument("--project", default=None, help="项目名称（单项目可省略）")
    p.add_argument("--key", required=True, help="商品唯一标识值")
    p.add_argument("--quantity", required=True, type=float, help="出库数量")
    p.add_argument("--type", default="sale", choices=["sale", "return", "damage", "other"], help="出库类型")
    p.add_argument("--remark", default="", help="备注")
    p.set_defaults(func=cmd_stock_out)

    # stock-query
    p = sub.add_parser("stock-query", help="库存查询")
    p.add_argument("--project", default=None, help="项目名称（单项目可省略）")
    p.add_argument("--key", default=None, help="商品唯一标识值（查单个）")
    p.add_argument("--low-stock", action="store_true", help="仅显示低库存商品")
    p.add_argument("--filter", default=None, help="精确筛选 字段名=值")
    p.set_defaults(func=cmd_stock_query)

    # stock-log
    p = sub.add_parser("stock-log", help="查看库存变动记录")
    p.add_argument("--project", default=None, help="项目名称（单项目可省略）")
    p.add_argument("--key", default=None, help="商品唯一标识值")
    p.add_argument("--direction", default=None, choices=["in", "out"], help="方向筛选")
    p.add_argument("--from", dest="from_date", default=None, help="起始日期 YYYY-MM-DD")
    p.add_argument("--to", dest="to_date", default=None, help="结束日期 YYYY-MM-DD")
    p.set_defaults(func=cmd_stock_log)

    # export
    p = sub.add_parser("export", help="导出数据为 CSV")
    p.add_argument("--project", default=None, help="项目名称（单项目可省略）")
    p.add_argument("--type", default="products", choices=["products", "logs"], help="导出类型")
    p.add_argument("--output", default=None, help="输出文件路径（默认自动生成）")
    p.set_defaults(func=cmd_export)

    args = parser.parse_args()
    return args.func(args)


if __name__ == "__main__":
    sys.exit(main())
