"""GitHub Issue Export — Export Preflight findings as GitHub issues.

Usage:
    preflight export-issues --repo https://github.com/user/repo --run ./artifacts/latest

Each issue becomes a GitHub issue with:
- Title from finding
- Labels: severity, category, "preflight"
- Body: user impact, repro steps, evidence
- Repair brief in a collapsible section
"""

from __future__ import annotations

import json
import logging
import subprocess
from pathlib import Path

from preflight.core.schemas import Issue, RunResult, Severity

logger = logging.getLogger(__name__)


def format_issue_body(issue: Issue) -> str:
    """Format a Preflight Issue into a GitHub issue body (markdown)."""
    parts: list[str] = []

    parts.append(f"**Severity:** {issue.severity.value}")
    parts.append(f"**Category:** {issue.category.value}")
    parts.append(f"**Platform:** {issue.platform.value}")
    parts.append(f"**Confidence:** {issue.confidence:.0%}")
    parts.append(f"**Agent:** {issue.agent}")
    parts.append("")

    if issue.user_impact:
        parts.append("## User Impact")
        parts.append(issue.user_impact)
        parts.append("")

    if issue.observed_facts:
        parts.append("## Evidence")
        for fact in issue.observed_facts:
            parts.append(f"- {fact}")
        parts.append("")

    if issue.inferred_judgment:
        parts.append("## Assessment")
        parts.append(issue.inferred_judgment)
        parts.append("")

    if issue.repro_steps:
        parts.append("## Repro Steps")
        for i, step in enumerate(issue.repro_steps, 1):
            parts.append(f"{i}. {step}")
        parts.append("")

    if issue.expected and issue.actual:
        parts.append(f"**Expected:** {issue.expected}")
        parts.append(f"**Actual:** {issue.actual}")
        parts.append("")

    if issue.evidence.screenshots:
        parts.append("## Screenshots")
        for s in issue.evidence.screenshots:
            parts.append(f"- `{s}`")
        parts.append("")

    if issue.repair_brief:
        parts.append("<details>")
        parts.append("<summary>Repair Brief</summary>")
        parts.append("")
        parts.append(issue.repair_brief)
        parts.append("")
        parts.append("</details>")
        parts.append("")

    parts.append("---")
    parts.append(f"*Generated by [Preflight](https://github.com/jxi5410/Preflight) "
                 f"| Issue ID: {issue.id}*")

    return "\n".join(parts)


def issue_labels(issue: Issue) -> list[str]:
    """Generate GitHub labels for an issue."""
    labels = ["preflight"]

    # Severity label
    severity_map = {
        "critical": "priority: critical",
        "high": "priority: high",
        "medium": "priority: medium",
        "low": "priority: low",
        "info": "priority: info",
    }
    labels.append(severity_map.get(issue.severity.value, "priority: medium"))

    # Category label
    labels.append(f"type: {issue.category.value}")

    return labels


def export_issues_via_gh(
    issues: list[Issue],
    repo: str,
    dry_run: bool = False,
    min_severity: str = "low",
) -> list[dict]:
    """Export issues to GitHub using the `gh` CLI.

    Args:
        issues: List of Preflight issues to export
        repo: GitHub repo in "owner/repo" or URL format
        dry_run: If True, format but don't actually create issues
        min_severity: Minimum severity to export (default: "low")

    Returns:
        List of dicts with export results (title, url, labels, or error)
    """
    # Normalize repo format
    repo_slug = repo
    if repo.startswith("https://github.com/"):
        repo_slug = repo.replace("https://github.com/", "").rstrip("/")

    # Filter by severity
    severity_threshold = {
        "critical": 0, "high": 1, "medium": 2, "low": 3, "info": 4,
    }
    threshold = severity_threshold.get(min_severity, 3)
    filtered = [
        i for i in issues
        if severity_threshold.get(i.severity.value, 5) <= threshold
    ]

    results: list[dict] = []

    for issue in filtered:
        body = format_issue_body(issue)
        labels = issue_labels(issue)
        title = f"[Preflight] {issue.title}"

        if dry_run:
            results.append({
                "title": title,
                "labels": labels,
                "body": body,
                "status": "dry_run",
            })
            continue

        try:
            label_args = []
            for label in labels:
                label_args.extend(["--label", label])

            cmd = [
                "gh", "issue", "create",
                "--repo", repo_slug,
                "--title", title,
                "--body", body,
                *label_args,
            ]

            proc = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                timeout=30,
            )

            if proc.returncode == 0:
                url = proc.stdout.strip()
                results.append({
                    "title": title,
                    "url": url,
                    "labels": labels,
                    "status": "created",
                })
                logger.info("Created issue: %s -> %s", title, url)
            else:
                results.append({
                    "title": title,
                    "status": "error",
                    "error": proc.stderr.strip(),
                })
                logger.warning("Failed to create issue '%s': %s", title, proc.stderr.strip())

        except FileNotFoundError:
            results.append({
                "title": title,
                "status": "error",
                "error": "gh CLI not found. Install: https://cli.github.com/",
            })
            logger.error("gh CLI not installed")
            break  # No point continuing
        except subprocess.TimeoutExpired:
            results.append({
                "title": title,
                "status": "error",
                "error": "gh command timed out",
            })

    return results


def export_summary(results: list[dict]) -> str:
    """Generate a human-readable summary of export results."""
    created = sum(1 for r in results if r.get("status") == "created")
    dry_run = sum(1 for r in results if r.get("status") == "dry_run")
    errors = sum(1 for r in results if r.get("status") == "error")

    parts = []
    if created:
        parts.append(f"{created} issues created")
    if dry_run:
        parts.append(f"{dry_run} issues (dry run)")
    if errors:
        parts.append(f"{errors} errors")

    return " | ".join(parts) if parts else "No issues to export"
