"""GitHub remote detection, workflow checks, and CI log fetching."""

from __future__ import annotations

import json
import re
import subprocess
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple


def get_github_remote(project_dir: Path) -> Optional[Tuple[str, str]]:
    """Return ``(owner, repo)`` from the ``origin`` remote, or ``None``."""
    try:
        result = subprocess.run(
            ["git", "remote", "get-url", "origin"],
            cwd=str(project_dir), capture_output=True, text=True, timeout=10,
        )
        m = re.search(r"github\.com[:/]([^/]+)/([^/.]+)", result.stdout.strip())
        if m:
            return m.group(1), m.group(2)
    except Exception:
        pass
    return None


def has_github_workflows(
    project_dir: Path, owner: str, repo: str,
) -> bool:
    """Return ``True`` if the repo has at least one GitHub Actions workflow."""
    try:
        result = subprocess.run(
            ["gh", "api", f"repos/{owner}/{repo}/actions/workflows",
             "--jq", ".total_count"],
            cwd=str(project_dir), capture_output=True, text=True, timeout=15,
        )
        if result.returncode == 0:
            return int(result.stdout.strip()) > 0
    except Exception:
        pass
    return False


def get_latest_workflow_run(
    project_dir: Path,
    owner: str,
    repo: str,
    head_sha: str,
    branch: str = "main",
) -> Optional[Dict[str, Any]]:
    """Fetch the latest GitHub Actions run for *head_sha* on *branch*."""
    try:
        jq_filter = (
            f'.workflow_runs | map(select(.head_sha == "{head_sha}" '
            f'and .head_branch == "{branch}")) | first'
        )
        result = subprocess.run(
            ["gh", "api", f"repos/{owner}/{repo}/actions/runs",
             "-q", jq_filter],
            cwd=str(project_dir), capture_output=True, text=True, timeout=30,
        )
        if (result.returncode == 0
                and result.stdout.strip()
                and result.stdout.strip() != "null"):
            return json.loads(result.stdout.strip())
    except Exception:
        pass
    return None


def get_head_sha(project_dir: Path, branch: str = "main") -> str:
    """Return the SHA of ``origin/<branch>``, or ``""``."""
    try:
        result = subprocess.run(
            ["git", "rev-parse", f"origin/{branch}"],
            cwd=str(project_dir), capture_output=True, text=True, timeout=10,
        )
        return result.stdout.strip()
    except Exception:
        return ""


def get_ci_failure_logs(
    project_dir: Path,
    owner: str,
    repo: str,
    run_id: int,
) -> str:
    """Fetch the failed-job logs for a workflow *run_id*.

    Returns the log text (truncated to 8 000 chars from the end).
    """
    logs_parts: List[str] = []
    try:
        result = subprocess.run(
            ["gh", "run", "view", str(run_id), "--repo", f"{owner}/{repo}",
             "--log-failed"],
            cwd=str(project_dir), capture_output=True, text=True, timeout=120,
        )
        if result.returncode == 0 and result.stdout:
            logs_parts.append(result.stdout)
    except Exception:
        pass
    full_logs = "\n".join(logs_parts)
    if len(full_logs) > 8000:
        full_logs = "... (truncated) ...\n" + full_logs[-8000:]
    return full_logs
