"""
Lenh `dsg setup` — cau hinh profiles, mo Chrome de dang nhap.
"""
from __future__ import annotations

import sys
import time

import click
import questionary

from ..config import load_settings, save_settings
from ..profile_manager import ensure_profile_exists
from ..browser_launcher import launch_chrome_for_login
from ..constants import SORA_URL
from .common import _LINE, _BOLD


def _setup_full() -> None:
    click.echo(f"\n{_BOLD}")
    click.echo("  SORA VIDEO TOOL — THIET LAP")
    click.echo(_BOLD)

    settings = load_settings()

    # ── Profiles ──────────────────────────────────────────────────────────
    click.echo("\n[1/4] Cau hinh profiles")
    num_options = [str(i) for i in range(1, 11)]
    default_num = str(min(settings.get("num_profiles", 1), 10))
    num_str = questionary.select(
        "  So luong profile",
        choices=num_options,
        default=default_num,
    ).ask()
    if num_str is None:
        return
    num = int(num_str)

    profiles: list[dict] = []
    for i in range(1, num + 1):
        alias = click.prompt(
            f"  Ten alias cho profile {i} (Enter = mac dinh)",
            default=f"Tai khoan {i}",
        )
        profiles.append({"id": f"profile_{i}", "alias": alias})

    # ── Credentials ───────────────────────────────────────────────────────
    click.echo("\n[2/4] Thong tin tai khoan")
    username = click.prompt("  Username dsora", default=settings.get("username", ""))
    backend_key = click.prompt(
        "  Backend key", hide_input=True, default=settings.get("backend_key", "")
    )

    # ── Telegram (optional) ───────────────────────────────────────────────
    click.echo("\n[3/4] Telegram (tuy chon — nhan Enter de bo qua)")
    tele_token = click.prompt(
        "  Bot Token", default=settings.get("telegram_token", ""), show_default=False
    )
    tele_channel = click.prompt(
        "  Channel ID", default=settings.get("telegram_channel", ""), show_default=False
    )

    # ── So phut cho giua moi san pham ──────────────────────────────────────
    click.echo("\n[4/4] So phut cho giua moi san pham")
    click.echo("  (Sau khi tao video, cho truoc khi chuyen sang san pham tiep. Co retry neu dang co 3 jobs.)")
    wait_min = click.prompt(
        "  So phut (mac dinh 10)",
        type=int,
        default=settings.get("wait_between_products_min", 10),
    )
    wait_min = max(1, min(wait_min, 120))  # clamp 1–120 phut

    # ── Save ──────────────────────────────────────────────────────────────
    settings.update({
        "num_profiles": num,
        "profiles": profiles,
        "username": username,
        "backend_key": backend_key,
        "telegram_token": tele_token,
        "telegram_channel": tele_channel,
        "wait_between_products_min": wait_min,
    })
    save_settings(settings)

    for p in profiles:
        ensure_profile_exists(p["id"])

    click.echo(f"\n{_LINE}")
    click.echo("  Cau hinh da luu.")
    click.echo(_LINE)
    click.echo("\nHuong dan sau khi Chrome mo:")
    click.echo("  1. Dang nhap Google trong moi cua so Chrome")
    click.echo("  2. Vao sora.com va dang nhap")
    click.echo("  3. Dong tat ca cua so Chrome khi xong")
    click.echo(_LINE)

    if click.confirm("\nMo Chrome de dang nhap ngay bay gio?", default=True):
        _open_browsers_for_login(profiles)


def _setup_retry() -> None:
    settings = load_settings()
    profiles = settings.get("profiles", [])

    if not profiles:
        click.echo("Chua co profile nao. Chay `dsg setup` truoc.", err=True)
        sys.exit(1)

    choices = [
        questionary.Choice(title=f"{p.get('alias', p['id'])} ({p['id']})", value=p, checked=True)
        for p in profiles
    ]
    selected = questionary.checkbox(
        "Chon profile de dang nhap lai (Space: chon/bo, Enter: xac nhan)",
        choices=choices,
    ).ask()

    if selected is None:
        return
    if not selected:
        click.echo("Khong co profile nao duoc chon.")
        return

    _open_browsers_for_login(selected)


def _open_browsers_for_login(profiles: list[dict]) -> None:
    for p in profiles:
        path = ensure_profile_exists(p["id"])
        click.echo(f"  Mo Chrome: {p['alias']} ...")
        launch_chrome_for_login(path, url=SORA_URL)
        time.sleep(0.8)

    click.echo(f"\nDa mo {len(profiles)} cua so Chrome.")
    click.echo("Dang nhap xong thi dong cac cua so la xong.")


def register_setup(main: click.Group) -> None:
    @main.command("setup")
    @click.option("--retry", is_flag=True, help="Mo lai profile cu de dang nhap lai.")
    def cmd_setup(retry: bool) -> None:
        """Cau hinh profiles, nhap thong tin, mo Chrome de dang nhap."""
        if retry:
            _setup_retry()
        else:
            _setup_full()
    return None
