from __future__ import annotations

import argparse
from dataclasses import replace

from .app import run_chat_app
from .config import Settings, SettingsError, load_settings


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="openkite",
        description="OpenKite trading assistant",
    )
    parser.add_argument(
        "command",
        nargs="?",
        default="chat",
        choices=["chat", "check"],
        help="chat: launch UI, check: validate configuration",
    )
    parser.add_argument(
        "--env-file",
        default=None,
        help="Path to .env file (default: auto-discover .env in working directory)",
    )
    parser.add_argument("--host", default=None, help="Override OPENKITE_HOST")
    parser.add_argument("--port", type=int, default=None, help="Override OPENKITE_PORT")
    parser.add_argument(
        "--share",
        action="store_true",
        help="Override OPENKITE_SHARE and request a public Gradio share link",
    )
    return parser


def _apply_overrides(settings: Settings, args: argparse.Namespace) -> Settings:
    overrides = {}
    if args.host:
        overrides["host"] = args.host
    if args.port:
        overrides["port"] = args.port
    if args.share:
        overrides["share"] = True
    if overrides:
        return replace(settings, **overrides)
    return settings


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

    try:
        settings = load_settings(args.env_file)
        settings = _apply_overrides(settings, args)
    except SettingsError as exc:
        parser.exit(2, f"Configuration error: {exc}\n")

    if args.command == "check":
        print("Configuration loaded successfully.")
        print(f"Model: {settings.model}")
        print(f"Kite SSE URL: {settings.kite_sse_url}")
        print(f"DB Path: {settings.db_path}")
        print(f"Host: {settings.host}:{settings.port}")
        print("OPENAI_API_KEY: set")
        print("FIRECRAWL_API_KEY: set")
        return 0

    try:
        run_chat_app(settings)
    except RuntimeError as exc:
        parser.exit(2, f"Startup error: {exc}\n")

    return 0


def entrypoint() -> int:
    return main()
