from __future__ import annotations

import argparse
import json
import sys

from customer_mgmt_core.service import CustomerManagementService

from .commands import customer, export_file, import_file, reminder, schema
from .config import CONFIG_FILE, resolve_db_path


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="客户管理 CLI")
    parser.add_argument(
        "--db",
        default=None,
        help="SQLite 数据库路径；不传时优先读取 ~/.config/sophnet-customer-management/config.env",
    )
    subparsers = parser.add_subparsers(dest="command", required=True)
    schema.register(subparsers)
    import_file.register(subparsers)
    customer.register(subparsers)
    reminder.register(subparsers)
    export_file.register(subparsers)
    return parser


def main() -> int:
    parser = build_parser()
    args = parser.parse_args()
    db_path = resolve_db_path(args.db)
    service = CustomerManagementService(db_path)
    try:
        result = args.handler(args, service)
    except Exception as exc:  # noqa: BLE001
        print(
            json.dumps(
                {
                    "ok": False,
                    "db_path": str(db_path),
                    "config_file": str(CONFIG_FILE),
                    "error": str(exc),
                },
                ensure_ascii=False,
                indent=2,
            )
        )
        return 1

    print(
        json.dumps(
            {
                "ok": True,
                "db_path": str(db_path),
                "config_file": str(CONFIG_FILE),
                "result": result,
            },
            ensure_ascii=False,
            indent=2,
        )
    )
    return 0


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