"""Vercel deployment monitoring: poll for deployment status and extract URLs."""

from __future__ import annotations

import json
import subprocess
import sys
import time
from pathlib import Path
from typing import Optional, Tuple

DEFAULT_VERCEL_TIMEOUT = 600
DEFAULT_VERCEL_POLL_INTERVAL = 10


def wait_for_vercel_deploy(
    project_dir: Path,
    *,
    timeout: int = DEFAULT_VERCEL_TIMEOUT,
    poll_interval: int = DEFAULT_VERCEL_POLL_INTERVAL,
    log=None,
) -> Tuple[bool, str]:
    """Block until the latest Vercel deployment completes.

    Returns ``(success, preview_url)``.  ``preview_url`` is ``""`` when
    no deployment was found or it failed.
    """
    if log is None:
        log = lambda msg: print(msg, file=sys.stderr)  # noqa: E731

    log(f"Waiting for Vercel deployment (up to {timeout}s)...")
    deadline = time.time() + timeout

    while time.time() < deadline:
        info = _get_latest_deployment(project_dir)
        if info is None:
            log("  No Vercel deployment found yet — waiting...")
            time.sleep(poll_interval)
            continue

        state = info.get("state", info.get("readyState", ""))
        url = info.get("url", "")

        if state in ("READY", "ready"):
            preview_url = f"https://{url}" if url and not url.startswith("http") else url
            log(f"Vercel deployment ready: {preview_url}")
            return True, preview_url

        if state in ("ERROR", "error", "CANCELED", "canceled"):
            log(f"Vercel deployment failed: state={state}")
            return False, ""

        log(f"  Vercel state: {state} — waiting...")
        time.sleep(poll_interval)

    log("Vercel deployment wait timed out.")
    return False, ""


def get_vercel_preview_url(
    project_dir: Path,
    *,
    log=None,
) -> str:
    """Return the preview URL of the latest Vercel deployment, or ``""``."""
    if log is None:
        log = lambda msg: print(msg, file=sys.stderr)  # noqa: E731

    info = _get_latest_deployment(project_dir)
    if info is None:
        return ""
    url = info.get("url", "")
    if url and not url.startswith("http"):
        url = f"https://{url}"
    return url


def _get_latest_deployment(project_dir: Path) -> Optional[dict]:
    """Fetch the latest deployment info via ``vercel list --json``."""
    try:
        result = subprocess.run(
            ["vercel", "list", "--json", "--limit", "1"],
            cwd=str(project_dir),
            capture_output=True,
            text=True,
            timeout=30,
        )
        if result.returncode != 0:
            return None

        data = json.loads(result.stdout.strip())

        if isinstance(data, list) and len(data) > 0:
            return data[0]

        if isinstance(data, dict):
            deployments = data.get("deployments", [])
            if deployments:
                return deployments[0]

    except (json.JSONDecodeError, FileNotFoundError, subprocess.TimeoutExpired):
        pass
    except Exception:
        pass
    return None
