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

import sys
import time

import click

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/5] Cau hinh profiles")
    num = click.prompt(
        "  So luong profile",
        type=int,
        default=settings.get("num_profiles", 1),
    )

    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/5] 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/5] 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
    )

    # ── Concurrent profiles ───────────────────────────────────────────────
    click.echo("\n[4/5] So luong Chrome chay cung luc")
    concurrent = click.prompt(
        f"  Mo dong thoi toi da (1-{num})",
        type=click.IntRange(1, max(num, 1)),
        default=min(settings.get("concurrent_profiles", 1), num),
    )

    # ── Run mode ──────────────────────────────────────────────────────────
    click.echo("\n[5/5] Che do chay san pham")
    click.echo("  1. Theo thu tu  — moi profile nhan mot lo SP co dinh (khuyen dung)")
    click.echo("  2. Tu do        — moi profile tu lay SP chua xu ly tu API")
    cur_mode = "1" if settings.get("run_mode", "ordered") == "ordered" else "2"
    mode_choice = click.prompt(
        "  Chon (1/2)", type=click.Choice(["1", "2"]), default=cur_mode
    )
    run_mode = "ordered" if mode_choice == "1" else "greedy"

    # ── Save ──────────────────────────────────────────────────────────────
    settings.update({
        "num_profiles": num,
        "profiles": profiles,
        "username": username,
        "backend_key": backend_key,
        "telegram_token": tele_token,
        "telegram_channel": tele_channel,
        "concurrent_profiles": concurrent,
        "run_mode": run_mode,
    })
    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 `sora setup` truoc.", err=True)
        sys.exit(1)

    click.echo(f"\n{_LINE}")
    click.echo("  CHON PROFILE DE DANG NHAP LAI")
    click.echo(_LINE)
    for i, p in enumerate(profiles, 1):
        click.echo(f"  {i}. {p['alias']}  ({p['id']})")
    click.echo(_LINE)

    raw = click.prompt(
        "Nhap so thu tu (cach nhau bang dau phay, Enter = tat ca)",
        default="all",
    )

    if raw.strip().lower() == "all":
        selected = profiles
    else:
        nums = [x.strip() for x in raw.split(",") if x.strip().isdigit()]
        selected = [profiles[int(n) - 1] for n in nums if 0 < int(n) <= len(profiles)]

    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
