"""Command line interface for evescaffold.

We intentionally use only the Python standard library here (argparse) to keep
the package lightweight and easy to install.
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

from .scaffold import add_model, init_project, list_builtin_models


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="evescaffold",
        description="EVE ML 项目脚手架：init / addmodel / list-models",
    )
    sub = parser.add_subparsers(dest="command", required=True)

    p_init = sub.add_parser("init", help="初始化项目目录骨架")
    p_init.add_argument(
        "--path",
        "-p",
        type=Path,
        default=None,
        help="项目根目录（默认当前目录）",
    )
    p_init.add_argument(
        "--force",
        action="store_true",
        help="覆盖已存在文件",
    )

    p_add = sub.add_parser("addmodel", help="初始化一个模型模板目录")
    p_add.add_argument("name", help="模型模板名，如 xgboost / randomForest / embeddingMLP")
    p_add.add_argument(
        "--path",
        "-p",
        type=Path,
        default=None,
        help="项目根目录（默认当前目录）",
    )
    p_add.add_argument(
        "--force",
        action="store_true",
        help="覆盖已存在文件",
    )

    sub.add_parser("list-models", help="列出内置模型模板")

    return parser


def main(argv: list[str] | None = None) -> None:
    parser = _build_parser()
    args = parser.parse_args(argv)

    base_dir = Path.cwd() if getattr(args, "path", None) is None else args.path

    if args.command == "init":
        init_project(base_dir=base_dir, force=bool(args.force))
        print(f"Initialized scaffold at: {base_dir}")
        return

    if args.command == "addmodel":
        model_dir = add_model(base_dir=base_dir, name=str(args.name), force=bool(args.force))
        print(f"Model scaffold created at: {model_dir}")
        return

    if args.command == "list-models":
        for item in list_builtin_models():
            print(f"- {item['name']}: {item['description']}")
        return

    # Should not happen due to argparse validation.
    parser.print_help(sys.stderr)
    raise SystemExit(2)
