#!/usr/bin/env python3
"""SwarmAgency — Python entry point with --model / --onboard flags.

Wraps `run_utils.main` so users can launch the TUI with explicit overrides
for the default model or run the setup wizard on demand. Equivalent of the
Node `bin/swarmagency` launcher for the Python side of the product.
"""

from __future__ import annotations

import argparse
import os
import sys


def _parse_args(argv: list[str]) -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        prog="swarmagency",
        description=(
            "SwarmAgency — multi-agent AI team. "
            "Launches the TUI after applying any pre-launch overrides."
        ),
    )
    parser.add_argument(
        "--model",
        metavar="MODEL_ID",
        default=None,
        help=(
            "Set DEFAULT_MODEL in the .env file before launching the TUI "
            "(e.g. 'deepseek/deepseek-v4-flash', 'minimax/MiniMax-M3'). "
            "Skips the interactive model picker."
        ),
    )
    parser.add_argument(
        "--onboard",
        action="store_true",
        help="Run the interactive setup wizard (provider + API keys + add-ons) before launching.",
    )
    return parser.parse_args(argv)


def _set_default_model(model_id: str) -> None:
    from dotenv import set_key

    from run_utils import _load_openswarm_dotenv, _openswarm_state_root

    env_path = _openswarm_state_root() / ".env"
    env_path.parent.mkdir(parents=True, exist_ok=True)
    if not env_path.exists():
        env_path.write_text("", encoding="utf-8")
    set_key(str(env_path), "DEFAULT_MODEL", model_id)
    _load_openswarm_dotenv(override=True)
    os.environ["DEFAULT_MODEL"] = model_id
    print(f"[swarmagency] DEFAULT_MODEL set to: {model_id}")


def main(argv: list[str] | None = None) -> None:
    args = _parse_args(sys.argv[1:] if argv is None else argv)

    if args.onboard:
        from onboard import run_onboarding
        run_onboarding()

    if args.model:
        _set_default_model(args.model)

    from run_utils import main as _run_main
    _run_main()


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\nCancelled.", file=sys.stderr)
        sys.exit(130)
