"""CI pipeline monitor — watches GitHub Actions and GitLab CI.

Called on BURN-E's heartbeat. Checks recent pipeline status,
matches failures against known patterns, and reports.
"""

from __future__ import annotations

import json
import os
import subprocess
from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path


@dataclass
class PipelineStatus:
    repo: str
    provider: str  # "github" or "gitlab"
    ref: str
    status: str  # "success", "failed", "running", "pending"
    url: str = ""
    failure_reason: str = ""

    def to_dict(self) -> dict:
        return {
            "repo": self.repo,
            "provider": self.provider,
            "ref": self.ref,
            "status": self.status,
            "url": self.url,
            "failure_reason": self.failure_reason,
        }


def check_pipelines() -> list[PipelineStatus]:
    """Check CI pipelines for all known repos. Called on BURN-E heartbeat."""
    results = []

    # Check GitHub (Axiom)
    gh = _check_github()
    if gh:
        results.append(gh)

    # Check GitLab (NeutronOS)
    gl = _check_gitlab()
    if gl:
        results.append(gl)

    return results


def _check_github() -> PipelineStatus | None:
    """Check latest GitHub Actions run for Axiom."""
    try:
        result = subprocess.run(
            ["gh", "run", "list", "-L", "1", "--json", "headBranch,status,conclusion,url"],
            capture_output=True,
            text=True,
            timeout=10,
            check=False,
        )
        if result.returncode != 0:
            return None

        runs = json.loads(result.stdout)
        if not runs:
            return None

        run = runs[0]
        status = run.get("conclusion", run.get("status", "unknown"))

        return PipelineStatus(
            repo="axiom",
            provider="github",
            ref=run.get("headBranch", ""),
            status=status,
            url=run.get("url", ""),
        )
    except Exception:
        return None


def _check_gitlab() -> PipelineStatus | None:
    """Check latest GitLab CI pipeline for NeutronOS."""
    token = os.environ.get("GITLAB_TOKEN", "")
    if not token:
        # Try reading from known location
        try:
            token_file = Path.home() / ".config" / "glab-cli" / "config.yml"
            if token_file.exists():
                import yaml

                cfg = yaml.safe_load(token_file.read_text())
                # Extract token from glab config
                hosts = cfg.get("hosts", {})
                for host_data in hosts.values():
                    if "token" in host_data:
                        token = host_data["token"]
                        break
        except Exception:
            pass

    if not token:
        return None

    try:
        import requests

        resp = requests.get(
            "https://rsicc-gitlab.tacc.utexas.edu/api/v4/projects/77/pipelines",
            headers={"PRIVATE-TOKEN": token},
            params={"per_page": 1},
            timeout=10,
        )
        if resp.status_code != 200:
            return None

        pipelines = resp.json()
        if not pipelines:
            return None

        p = pipelines[0]
        return PipelineStatus(
            repo="neutron-os",
            provider="gitlab",
            ref=p.get("ref", ""),
            status=p.get("status", "unknown"),
            url=p.get("web_url", ""),
        )
    except Exception:
        return None


def get_build_status() -> dict:
    """Get comprehensive build status for both repos."""
    from .mode import detect_mode

    mode = detect_mode()
    pipelines = check_pipelines()

    return {
        "mode": mode.to_dict(),
        "pipelines": [p.to_dict() for p in pipelines],
        "all_green": all(p.status == "success" for p in pipelines),
        "checked_at": datetime.now(UTC).isoformat(),
    }
