"""CLI: python -m iuve_connect_agents.desktop.ui_bridge"""

from __future__ import annotations

import argparse
import json
import os
import sys
import webbrowser
from pathlib import Path

from .auth import resolve_or_create_token
from .ensure import ensure_bridge, launch_console
from .server import DEFAULT_HOST, DEFAULT_PORT, UiBridgeServer, default_ui_web_root


def _default_config_path() -> Path:
    return Path.home() / ".config" / "iuve-connect-agent" / "desktop-config.json"


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="IuVe Connect UI Bridge (Phase C)")
    parser.add_argument("--host", default=os.environ.get("IUVE_UI_BRIDGE_HOST", DEFAULT_HOST))
    parser.add_argument(
        "--port",
        type=int,
        default=int(os.environ.get("IUVE_UI_BRIDGE_PORT") or DEFAULT_PORT),
    )
    parser.add_argument("--config", default=str(_default_config_path()))
    parser.add_argument("--ui-root", default=str(default_ui_web_root()))
    parser.add_argument("--open", action="store_true", help="Open console URL in default browser")
    parser.add_argument("--print-url", action="store_true", help="Print console URL JSON and exit setup only")
    parser.add_argument(
        "--ensure",
        action="store_true",
        help="Ensure bridge is running (spawn if needed), print JSON, exit",
    )
    parser.add_argument(
        "--launch-console",
        action="store_true",
        help="Ensure bridge + open Console (pywebview if available)",
    )
    parser.add_argument(
        "--no-webview",
        action="store_true",
        help="With --launch-console, force system browser instead of pywebview",
    )
    args = parser.parse_args(argv)

    config_path = Path(args.config)

    if args.ensure:
        meta = ensure_bridge(
            host=str(args.host),
            port=int(args.port),
            config_path=config_path if config_path.is_file() else None,
            ui_root=Path(args.ui_root),
        )
        print(json.dumps(meta, ensure_ascii=True, sort_keys=True))
        return 0 if meta.get("ok") else 1

    if args.launch_console:
        os.environ.setdefault("IUVE_AGENT_PYTHON", sys.executable)
        meta = launch_console(
            config_path=config_path if config_path.is_file() else None,
            open_ui=True,
            prefer_webview=not bool(args.no_webview),
        )
        printable = {k: v for k, v in meta.items() if k != "opener"}
        print(json.dumps(printable, ensure_ascii=True, sort_keys=True))
        if meta.get("opener"):
            print(json.dumps({"opener": meta["opener"]}, ensure_ascii=True, sort_keys=True))
        return 0 if meta.get("ok") else 1

    token = resolve_or_create_token()
    server = UiBridgeServer(
        token=token,
        host=str(args.host),
        port=int(args.port),
        ui_root=Path(args.ui_root),
        config_path=config_path if config_path.is_file() else None,
    )
    meta = {
        "ok": True,
        "service": "ui_bridge",
        "phase": "C.3",
        "ui_surface": "native_console",
        "base_url": server.base_url,
        "console_url": server.console_url,
        "ui_root": str(server.ui_root),
        "config_path": str(config_path) if config_path.is_file() else None,
        "bind": f"{server.host}:{server.port}",
    }
    print(json.dumps(meta, ensure_ascii=True, sort_keys=True))
    if args.print_url:
        return 0
    if args.open:
        webbrowser.open(server.console_url)
    try:
        server.start(background=False)
    except KeyboardInterrupt:
        server.stop()
        return 0
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
