"""
Lenh `dsg share` — tu dong tao share link cho cac video NEW trong ngay.

Flow moi profile:
1. Mo Chrome, vao trang chu Sora
2. Tim tat ca video co badge NEW (scroll de load them)
3. Vao tung video:
   a. Click nut 3 cham (retry neu menu chua xuat hien)
   b. Click "Copy link" trong popover
   c. Xac nhan trong modal "Copy link to video?"
   d. Cho 2s roi doc clipboard lay share link
   e. Goi API POST /sora-videos luu share link
4. Dong Chrome, sang profile tiep theo
"""
from __future__ import annotations

import html as html_lib
import re
import subprocess
import sys
import time

import click
import questionary

from ..api_client import add_sora_video
from ..browser_launcher import close_chrome, launch_chrome_for_automation
from ..config import load_settings, validate_settings
from ..constants import CDP_PORT_BASE, SORA_URL
from ..profile_manager import ensure_profile_exists
from .common import _BOLD


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _read_clipboard(page) -> str:
    """Doc noi dung clipboard. macOS dung pbpaste, fallback browser clipboard API."""
    if sys.platform == "darwin":
        try:
            result = subprocess.run(
                ["pbpaste"], capture_output=True, text=True, timeout=3
            )
            if result.returncode == 0 and result.stdout.strip():
                return result.stdout.strip()
        except Exception:
            pass
    try:
        return page.evaluate("async () => await navigator.clipboard.readText()") or ""
    except Exception:
        return ""


def _get_new_video_hrefs(page) -> list[tuple[str, str | None]]:
    """
    Scroll de load them video, lay raw HTML, parse theo tung card (data-index).
    Card co badge NEW va href /d/gen_... la video chua share.
    Tra ve danh sach tuple (page_url, video_src) — video_src co the la None.
    """
    # Scroll xuong cuoi roi len dau de load het video
    page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
    time.sleep(1.5)
    page.evaluate("window.scrollTo(0, 0)")
    time.sleep(0.5)

    html = page.content()
    base_url = "https://sora.chatgpt.com"

    # Tach HTML thanh tung card theo data-index
    cards = re.split(r'(?=<div data-index="\d+")', html)

    seen: set[str] = set()
    results: list[tuple[str, str | None]] = []
    for card in cards:
        # Chi lay card co badge NEW (span text "NEW")
        if not re.search(r'>NEW<', card):
            continue
        # Tim href /d/gen_... (chua share); /p/s_... la da share
        href_match = re.search(r'<a\s+href="(/d/[^"]+)"', card)
        if not href_match:
            continue
        page_url = base_url + href_match.group(1)
        if page_url in seen:
            continue
        seen.add(page_url)
        # Lay video src (URL day du, bat dau bang https://)
        src_match = re.search(r'<video\s+src="(https://[^"]+)"', card)
        video_src = html_lib.unescape(src_match.group(1)) if src_match else None
        results.append((page_url, video_src))

    return results


def _click_three_dot_btn(page) -> bool:
    """
    Tim va click nut 3 cham (SVG voi 3 hinh tron).
    Tra ve True neu menu [role=menuitem] xuat hien sau khi click.
    """
    try:
        # Path SVG cua nut 3 cham bat dau voi "M3 12a2 2"
        btn = page.locator('button:has(path[d*="M3 12a2 2 0 1 1 4 0"])').first
        btn.wait_for(state="visible", timeout=5_000)
        btn.click()
        time.sleep(0.8)
        return page.locator('[role="menuitem"]').count() > 0
    except Exception:
        return False


def _get_share_link_for_video(page, video_url: str, alias: str) -> str | None:
    """
    Vao trang video, thuc hien quy trinh tao share link, doc clipboard.
    Tra ve share URL neu thanh cong, None neu that bai.
    """
    try:
        page.goto(video_url, wait_until="domcontentloaded", timeout=30_000)
        time.sleep(1.5)

        # --- Buoc 1: Click nut 3 cham, retry neu menu chua hien ---
        menu_ok = False
        for attempt in range(3):
            menu_ok = _click_three_dot_btn(page)
            if menu_ok:
                break
            click.echo(f"    [{alias}] Menu chua hien, thu lai ({attempt + 1}/3)...")
            time.sleep(1)

        if not menu_ok:
            click.echo(f"    [{alias}] Khong mo duoc menu 3 cham.")
            return None

        # --- Buoc 2: Click "Copy link" trong popover ---
        try:
            copy_item = page.locator('[role="menuitem"]:has-text("Copy link")').first
            copy_item.click(timeout=5_000)
        except Exception:
            click.echo(f"    [{alias}] Khong tim thay 'Copy link' trong menu.")
            return None
        time.sleep(0.5)

        # --- Buoc 3: Xac nhan trong modal "Copy link to video?" ---
        modal = page.locator('h2:has-text("Copy link to video?")')
        if modal.count() == 0:
            click.echo(f"    [{alias}] Modal xac nhan khong hien.")
            return None

        try:
            # Nut "Copy link" chinh (khong phai Cancel) la button cuoi cung
            confirm_btn = page.get_by_role("button", name="Copy link", exact=True).last
            confirm_btn.click(timeout=5_000)
        except Exception:
            click.echo(f"    [{alias}] Khong bam duoc nut xac nhan.")
            return None

        # --- Buoc 4: Cho link vao clipboard roi doc ---
        time.sleep(2)
        link = _read_clipboard(page)

        if link and any(
            domain in link
            for domain in ("sora.com", "sora.chatgpt.com", "chatgpt.com")
        ):
            return link

        click.echo(
            f"    [{alias}] Link clipboard khong hop le: "
            f"'{link[:80] if link else '(trong)'}'"
        )
        return None

    except Exception as e:
        click.echo(f"    [{alias}] Loi xu ly video: {e}")
        return None


# ---------------------------------------------------------------------------
# Profile processor
# ---------------------------------------------------------------------------

def _process_profile_shares(
    profile: dict,
    profile_idx: int,
    settings: dict,
    counters: dict,
) -> None:
    """Mo Chrome cho 1 profile, tim va tao share link cho tat ca video NEW."""
    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

    try:
        proc, pw, _browser, context, page = launch_chrome_for_automation(
            profile_path, debug_port
        )

        # Cap quyen doc/ghi clipboard cho trang Sora
        try:
            context.grant_permissions(["clipboard-read", "clipboard-write"])
        except Exception:
            pass

        # Ve trang drafts de xem danh sach video
        page.goto("https://sora.chatgpt.com/drafts", wait_until="domcontentloaded", timeout=30_000)
        time.sleep(2)

        # Cho video load: kiem tra moi 5s, toi da 30s
        videos: list[tuple[str, str | None]] = []
        waited = 0
        max_wait = 30
        interval = 5
        while waited <= max_wait:
            videos = _get_new_video_hrefs(page)
            if videos:
                break
            if waited < max_wait:
                click.echo(
                    f"  [{alias}] Chua co video NEW, cho them {interval}s "
                    f"({waited}/{max_wait}s)..."
                )
                time.sleep(interval)
            waited += interval

        if not videos:
            click.echo(f"  [{alias}] Khong co video NEW sau {max_wait}s.")
            return

        click.echo(f"  [{alias}] Tim thay {len(videos)} video NEW.")

        for i, (href, video_src) in enumerate(videos, 1):
            click.echo(f"\n    [{alias}] ({i}/{len(videos)}) {href}")
            if video_src:
                click.echo(f"    [{alias}] MP4: {video_src[:80]}...")
            link = _get_share_link_for_video(page, href, alias)

            if link:
                click.echo(f"    [{alias}] Share link: {link}")
                try:
                    add_sora_video(
                        link,
                        settings["username"],
                        settings["backend_key"],
                        sora_mp4_share_link=video_src,
                    )
                    counters["done"] += 1
                    click.echo(f"    [{alias}] Da luu thanh cong.")
                except Exception as api_err:
                    click.echo(f"    [{alias}] Loi API: {api_err}")
                    counters["failed"] += 1
            else:
                counters["failed"] += 1

            # Quay ve trang drafts truoc khi xu ly video tiep theo
            page.goto("https://sora.chatgpt.com/drafts", wait_until="domcontentloaded", timeout=30_000)
            time.sleep(1.5)

    except Exception as e:
        click.echo(f"  LOI [{alias}]: {e}")
    finally:
        if pw:
            try:
                pw.stop()
            except Exception:
                pass
        if proc:
            close_chrome(proc)
            click.echo(f"  Da dong Chrome: {alias}")


# ---------------------------------------------------------------------------
# CLI command
# ---------------------------------------------------------------------------

def cmd_share() -> None:
    """Tao share link cho cac video NEW cua moi profile va luu vao he thong."""
    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"]
    if not profiles:
        click.echo("Chua co profile nao. Chay `dsg setup` truoc.")
        sys.exit(1)

    if len(profiles) == 1:
        selected = profiles
    else:
        choices = [
            questionary.Choice(
                title=f"{p.get('alias', p['id'])} ({p['id']})", value=p, checked=False
            )
            for p in profiles
        ]
        selected = questionary.checkbox(
            "Chon profile can lay share link (Space: chon/bo, Enter: xac nhan)",
            choices=choices,
        ).ask()
        if not selected:
            click.echo("Khong co profile nao duoc chon.")
            sys.exit(0)

    counters: dict = {"done": 0, "failed": 0}

    click.echo(f"\n{_BOLD}")
    click.echo("  SORA SHARE LINK TOOL")
    click.echo(_BOLD)
    click.echo(f"  Username  : {settings['username']}")
    click.echo(
        f"  Profiles  : {', '.join(p.get('alias', p['id']) for p in selected)}"
    )
    click.echo(_BOLD)

    for profile in selected:
        profile_idx = next(
            (i for i, p in enumerate(profiles) if p["id"] == profile["id"]), 0
        )
        click.echo(f"\n  Profile: {profile.get('alias', profile['id'])}")
        _process_profile_shares(profile, profile_idx, settings, counters)

    click.echo(f"\n{_BOLD}")
    click.echo("  HOAN TAT")
    click.echo(_BOLD)
    click.echo(f"  Share link da luu : {counters['done']}")
    click.echo(f"  Loi               : {counters['failed']}")
    click.echo(_BOLD)


def register_share(main: click.Group) -> None:
    main.command("share")(cmd_share)
