"""
Cac lenh phu: open, update, help, check.
"""
from __future__ import annotations

import subprocess
import sys

import click
import questionary

from ..config import load_settings, validate_settings, SETTINGS_FILE
from ..profile_manager import ensure_profile_exists, get_profile_path, PROFILES_DIR
from ..browser_launcher import launch_chrome_for_login
from ..constants import SORA_URL, PRODUCTS_PER_PROFILE
from .common import _LINE, _BOLD


def register_open(main: click.Group) -> None:
    @main.command("open")
    @click.argument("alias", required=False)
    def cmd_open(alias: str | None) -> None:
        """Mo Chrome cho mot profile. Neu khong truyen alias thi chon tu danh sach."""
        settings = load_settings()
        profiles = settings.get("profiles", [])

        if not profiles:
            click.echo("Chua co profile nao. Chay: dsg setup")
            sys.exit(1)

        if alias:
            match = next(
                (p for p in profiles if (p.get("alias") or p["id"]).lower() == alias.lower()),
                None,
            )
            if match is None:
                available = ", ".join(p.get("alias", p["id"]) for p in profiles)
                click.echo(f"Khong tim thay profile '{alias}'. Cac profile: {available}")
                sys.exit(1)
        else:
            choices = [
                questionary.Choice(title=f"{p.get('alias', p['id'])} ({p['id']})", value=p)
                for p in profiles
            ]
            match = questionary.select(
                "Chon profile de mo Chrome",
                choices=choices,
            ).ask()
            if match is None:
                sys.exit(0)

        profile_path = ensure_profile_exists(match["id"])
        click.echo(f"Mo Chrome: {match['alias']} ({match['id']}) ...")
        proc = launch_chrome_for_login(profile_path, url=SORA_URL)
        click.echo("Dong cua so Chrome khi xong.")
        proc.wait()


def register_update(main: click.Group) -> None:
    @main.command("update")
    def cmd_update() -> None:
        """Cap nhat dsora-gen len phien ban moi nhat."""
        exe = sys.executable

        if "pipx" in exe or "pipx" in sys.argv[0]:
            click.echo("Cap nhat qua pipx ...")
            cmd = ["pipx", "upgrade", "dsora-gen"]
        else:
            click.echo("Cap nhat qua pip ...")
            cmd = [exe, "-m", "pip", "install", "--upgrade", "dsora-gen"]

        result = subprocess.run(cmd)
        if result.returncode == 0:
            click.echo("\nCap nhat thanh cong!")
        else:
            click.echo("\nCap nhat that bai. Thu chay thu cong:", err=True)
            click.echo("  pipx upgrade dsora-gen", err=True)
            click.echo("  hoac: pip3 install --upgrade dsora-gen", err=True)
            sys.exit(result.returncode)


def register_check(main: click.Group) -> None:
    @main.command("check")
    def cmd_check() -> None:
        """Kiem tra setup hien tai (config, profiles, san sang chay)."""
        settings = load_settings()

        click.echo(f"\n{_BOLD}")
        click.echo("  KIEM TRA SETUP")
        click.echo(_BOLD)

        # File cau hinh
        click.echo(f"\n  File cau hinh : {SETTINGS_FILE}")
        click.echo(f"  Ton tai      : {'Co' if SETTINGS_FILE.exists() else 'Khong'}")

        if not settings:
            click.echo(f"\n  {_LINE}")
            click.echo("  Chua co cau hinh. Chay: dsg setup")
            click.echo(_LINE)
            return

        # Tai khoan
        username = settings.get("username", "")
        backend_key = settings.get("backend_key", "")
        click.echo(f"\n  Username     : {username or '(trong)'}")
        click.echo(f"  Backend key  : {'***' if backend_key else '(trong)'}")

        # Telegram
        has_tele = bool(settings.get("telegram_token") and settings.get("telegram_channel"))
        click.echo(f"  Telegram     : {'Da cau hinh' if has_tele else 'Chua cau hinh'}")

        wait_min = settings.get("wait_between_products_min", 10)
        click.echo(f"  Che do       : Chay lan luot tung profile (chon khi chay lenh run)")
        click.echo(f"  Cho giua SP  : {wait_min} phut")

        # Profiles
        profiles = settings.get("profiles", [])
        click.echo(f"\n  Profiles     : {len(profiles)}")
        for i, p in enumerate(profiles, 1):
            pid = p.get("id", "")
            alias = p.get("alias", pid)
            path = get_profile_path(pid)
            exists = path.exists() and path.is_dir()
            status = "OK" if exists else "Chua tao thu muc"
            click.echo(f"    {i}. {alias} ({pid}) — {status}")

        click.echo(f"\n  Thu muc profiles : {PROFILES_DIR}")

        # Kiem tra co the chay run khong
        click.echo(f"\n  {_LINE}")
        try:
            validate_settings(settings)
            max_products = len(profiles) * PRODUCTS_PER_PROFILE if profiles else 0
            click.echo(f"  San sang chay : Co (toi da {max_products} san pham/phan lo)")
        except ValueError as e:
            click.echo(f"  San sang chay : Khong — {e}")
        click.echo(_LINE)
        click.echo()


def register_uninstall(main: click.Group) -> None:
    @main.command("uninstall")
    def cmd_uninstall() -> None:
        """Go cai dsora-gen va xoa du lieu trong ~/.sora-tool/."""
        from ..constants import APP_DATA_DIR
        import shutil

        click.echo("\n  DSORA-GEN UNINSTALL")
        click.echo("  " + "=" * 40)
        click.echo(f"  Se xoa: {APP_DATA_DIR}")
        click.echo("  Se go cai package dsora-gen")
        click.echo()

        confirmed = click.confirm("  Ban chac chan muon go cai khong?", default=False)
        if not confirmed:
            click.echo("  Da huy.")
            return

        # Xoa thu muc du lieu
        if APP_DATA_DIR.exists():
            shutil.rmtree(APP_DATA_DIR)
            click.echo(f"  Da xoa: {APP_DATA_DIR}")
        else:
            click.echo(f"  Khong tim thay thu muc: {APP_DATA_DIR}")

        # Go cai package
        exe = sys.executable
        if "pipx" in exe or "pipx" in sys.argv[0]:
            click.echo("  Go cai qua pipx ...")
            cmd = ["pipx", "uninstall", "dsora-gen"]
        else:
            click.echo("  Go cai qua pip ...")
            cmd = [exe, "-m", "pip", "uninstall", "-y", "dsora-gen"]

        result = subprocess.run(cmd)
        if result.returncode == 0:
            click.echo("\n  Go cai thanh cong!")
        else:
            click.echo("\n  Go cai that bai. Thu chay thu cong:", err=True)
            click.echo("  pipx uninstall dsora-gen", err=True)
            click.echo("  hoac: pip3 uninstall dsora-gen", err=True)
            sys.exit(result.returncode)


def register_help(main: click.Group) -> None:
    @main.command("help")
    @click.pass_context
    def cmd_help(ctx: click.Context) -> None:
        """Hien thi danh sach lenh."""
        click.echo(ctx.parent.get_help())  # type: ignore[union-attr]
