"""
Lenh `dsg run` — chay lan luot tung profile (user chon).

Flow: moi lan chi mo 1 Chrome profile. Sau khi submit xong 1 san pham (thanh cong hoac loi)
thi dong Chrome roi ngay lap tuc mo profile tiep theo. Lap round-robin den khi het SP hoac tat ca profile dat limit.
"""
from __future__ import annotations

import sys

import click
import questionary

from ..config import load_settings, validate_settings
from ..profile_manager import ensure_profile_exists
from ..browser_launcher import launch_chrome_for_automation, close_chrome
from ..sora_bot import create_video, VideoGenLimitReachedError
from ..api_client import get_pending_products, mark_product_done
from ..telegram_notifier import (
    notify_product_done,
    notify_product_failed,
    notify_profile_limit_reached,
    notify_all_done,
)
from ..run_tracker import record_product_done, record_product_failed
from ..constants import CDP_PORT_BASE
from .common import _LINE, _BOLD, image_src


def _process_one_product(
    profile: dict,
    profile_idx: int,
    settings: dict,
    counters: dict,
) -> bool:
    """
    Mo Chrome, xu ly dung 1 san pham, dong Chrome.
    Tra ve True neu profile dat limit (can loai khoi vong tiep theo).
    """
    profile_id = profile["id"]
    alias = profile.get("alias", profile_id)
    debug_port = CDP_PORT_BASE + profile_idx
    profile_path = ensure_profile_exists(profile_id)
    proc = pw = None
    current_pid: int | None = None

    try:
        fresh = get_pending_products(settings["username"])
        if not fresh:
            return False

        product = fresh[0]
        current_pid = product["id"]
        pname = product["product_name"]
        prompt = product["prompt_content"]
        image_src_val = image_src(
            product.get("product_image") or product.get("image_url")
        )

        click.echo(f"\n  [{alias}] {pname}")
        click.echo(f"  Anh: {image_src_val or '(mac dinh)'}")

        proc, pw, _browser, _ctx, page = launch_chrome_for_automation(profile_path, debug_port)

        try:
            create_video(page, prompt, image_src_val, profile_alias=alias)
            mark_product_done(current_pid, settings["backend_key"])
            counters["done"] += 1
            record_product_done(profile_id, current_pid)
            click.echo(f"  OK  [{alias}] {pname}")
            notify_product_done(settings, alias, pname)
            return False
        except VideoGenLimitReachedError:
            counters["failed"] += 1
            record_product_failed(profile_id)
            click.echo(f"  [GIOI HAN] [{alias}] {pname}: da tao toi da video trong ngay.")
            notify_profile_limit_reached(settings, alias)
            click.echo(f"  [GIOI HAN] {alias}: Tat profile, bo qua profile nay o cac vong sau.")
            return True  # hit limit -> remove from active
        except Exception as e:
            counters["failed"] += 1
            record_product_failed(profile_id)
            click.echo(f"  LOI  [{alias}] {pname}: {e}")
            notify_product_failed(settings, alias, pname, str(e))
            return False
        finally:
            current_pid = None

    except Exception as e:
        click.echo(f"  LOI  [{alias}]: {e}")
        if current_pid is not None:
            pass
        counters["failed"] += 1
        return False
    finally:
        if pw:
            try:
                pw.stop()
            except Exception:
                pass
        if proc:
            close_chrome(proc)
            click.echo(f"  Da dong Chrome: {alias}")


def _select_profiles_for_run(profiles: list[dict]) -> list[dict] | None:
    """Hien thi checkbox chon profile chay trong session. Tra ve None neu user huy."""
    if not profiles:
        return None
    if len(profiles) == 1:
        return profiles

    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 chay trong session (Space: chon/bỏ, Enter: xac nhan)",
        choices=choices,
    ).ask()

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


def cmd_run() -> None:
    """Chay tu dong tao video: chon profile, round-robin — moi profile lam 1 SP roi dong, chuyen profile tiep theo."""
    settings = load_settings()

    try:
        validate_settings(settings)
    except ValueError as e:
        click.echo(f"Loi cau hinh: {e}", err=True)
        sys.exit(1)

    profiles = settings["profiles"]
    selected = _select_profiles_for_run(profiles)
    if selected is None:
        sys.exit(0)

    counters: dict = {"done": 0, "failed": 0}
    active_profiles = list(selected)  # profile dat limit se bi loai

    click.echo(f"\n{_BOLD}")
    click.echo("  SORA VIDEO TOOL — CHAY (1 SP/profile, dong roi next)")
    click.echo(_BOLD)
    click.echo(f"  Username       : {settings['username']}")
    click.echo(f"  Profiles chay  : {', '.join(p.get('alias', p['id']) for p in active_profiles)}")
    click.echo(_BOLD)

    while active_profiles:
        try:
            pending = get_pending_products(settings["username"])
        except Exception as e:
            click.echo(f"  Loi fetch API: {e}")
            break
        if not pending:
            click.echo("\n  Khong con san pham pending.")
            break

        still_active = []
        for profile in active_profiles:
            try:
                pending = get_pending_products(settings["username"])
                if not pending:
                    break
            except Exception:
                pass
            # Port CDP co dinh theo thu tu profile trong settings
            profile_idx = next(
                (i for i, p in enumerate(profiles) if p["id"] == profile["id"]),
                0,
            )
            hit_limit = _process_one_product(profile, profile_idx, settings, counters)
            if not hit_limit:
                still_active.append(profile)

        active_profiles = still_active
        if not active_profiles:
            click.echo("\n  Tat ca profile da dat limit hoac khong con profile active.")

    click.echo(f"\n{_BOLD}")
    click.echo("  HOAN TAT")
    click.echo(_BOLD)
    click.echo(f"  Thanh cong : {counters['done']}")
    click.echo(f"  Loi        : {counters['failed']}")
    click.echo(f"  Tong       : {counters['done'] + counters['failed']}")
    click.echo(_BOLD)

    notify_all_done(settings, counters["done"], counters["failed"])


def register_run(main: click.Group) -> None:
    main.command("run")(cmd_run)
