"""CI monitoring: poll GitHub Actions until a workflow run completes."""

from __future__ import annotations

import sys
import time
from pathlib import Path
from typing import Tuple

from autobuilder_hook_helpers.github import get_latest_workflow_run

DEFAULT_CI_TIMEOUT = 600
DEFAULT_CI_POLL_INTERVAL = 15


def wait_for_ci(
    project_dir: Path,
    owner: str,
    repo: str,
    head_sha: str,
    *,
    branch: str = "main",
    timeout: int = DEFAULT_CI_TIMEOUT,
    poll_interval: int = DEFAULT_CI_POLL_INTERVAL,
    log=None,
) -> Tuple[bool, int]:
    """Block until the CI run for *head_sha* completes.

    Returns ``(passed, run_id)``.  ``run_id`` is 0 when no run was found
    before *timeout* expired.
    """
    if log is None:
        log = lambda msg: print(msg, file=sys.stderr)  # noqa: E731

    log(f"Waiting for CI (sha={head_sha[:8]}..., up to {timeout}s)...")
    deadline = time.time() + timeout

    while time.time() < deadline:
        run = get_latest_workflow_run(
            project_dir, owner, repo, head_sha, branch=branch,
        )
        if run:
            status = run.get("status", "")
            conclusion = run.get("conclusion", "")
            run_id = run.get("id", 0)
            if status == "completed":
                if conclusion == "success":
                    log(f"CI passed (run {run_id})")
                    return True, run_id
                log(f"CI failed: conclusion={conclusion} (run {run_id})")
                return False, run_id
            log(f"  CI status: {status} — waiting...")
        else:
            log("  No workflow run found yet — waiting...")
        time.sleep(poll_interval)

    log("CI wait timed out.")
    return False, 0
