"""agentkit setup-ci command — one-command CI onboarding."""
from __future__ import annotations

import subprocess
import sys
from pathlib import Path
from typing import Optional

import typer
from rich.console import Console
from rich.panel import Panel

from agentkit_cli.config import find_project_root

console = Console()

# ---------------------------------------------------------------------------
# Workflow template
# ---------------------------------------------------------------------------

WORKFLOW_TEMPLATE = """\
# Generated by agentkit setup-ci
name: agentkit quality

on:
  push:
    branches: [main, master]
  pull_request:

jobs:
  quality:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install agentkit-cli and toolkit
        run: |
          pip install agentkit-cli
          pip install agentlint agentmd coderace agentreflect || true

      - name: Run agentkit gate
        run: |
          if [ -f ".agentkit-baseline.json" ]; then
            agentkit gate --min-score {min_score} --json --job-summary --baseline-report .agentkit-baseline.json
          else
            agentkit gate --min-score {min_score} --json --job-summary
          fi

      - name: Generate badge
        if: github.event_name == 'push'
        run: agentkit badge --json || true

      - name: Post PR comment
        if: github.event_name == 'pull_request' && always()
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const summary = process.env.GITHUB_STEP_SUMMARY;
            if (!summary || !fs.existsSync(summary)) return;
            const body = fs.readFileSync(summary, 'utf8');
            await github.rest.issues.createComment({{
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: body
            }});
"""


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _is_github_repo(root: Path) -> bool:
    """Return True if the git remote is on github.com."""
    git_config = root / ".git" / "config"
    if not git_config.exists():
        return False
    try:
        content = git_config.read_text(encoding="utf-8")
        return "github.com" in content
    except OSError:
        return False


def _run_baseline(root: Path) -> bool:
    """Run agentkit report --json --output .agentkit-baseline.json.

    Returns True on success, False on failure.
    """
    baseline_path = root / ".agentkit-baseline.json"
    try:
        result = subprocess.run(
            [sys.executable, "-m", "agentkit_cli.main", "report", "--json", "--output", str(baseline_path)],
            cwd=str(root),
            capture_output=True,
            text=True,
            timeout=120,
        )
        if result.returncode != 0:
            # Try via the installed agentkit binary as fallback
            result2 = subprocess.run(
                ["agentkit", "report", "--json", "--output", str(baseline_path)],
                cwd=str(root),
                capture_output=True,
                text=True,
                timeout=120,
            )
            return result2.returncode == 0
        return True
    except (OSError, subprocess.TimeoutExpired):
        return False


def _inject_badge(root: Path) -> bool:
    """Inject badge into README.md using the existing readme_cmd logic.

    Returns True if injected, False if skipped/failed.
    """
    readme = root / "README.md"
    if not readme.exists():
        return False
    try:
        from agentkit_cli.commands.readme_cmd import readme_command
        readme_command(
            readme=None,
            dry_run=False,
            remove=False,
            section_header="## Agent Quality",
            path=root,
            score_override=None,
        )
        return True
    except Exception:  # noqa: BLE001
        return False


# ---------------------------------------------------------------------------
# Command
# ---------------------------------------------------------------------------

def setup_ci_command(
    min_score: int,
    workflow_path: Optional[Path],
    force: bool,
    dry_run: bool,
    skip_baseline: bool,
    no_badge: bool,
    path: Optional[Path],
) -> None:
    """One-command CI setup: write GitHub Actions workflow, generate baseline, inject badge."""
    root = path or find_project_root()
    root = root.resolve()

    # --- Resolve workflow path ---
    if workflow_path is None:
        wf_path = root / ".github" / "workflows" / "agentkit-quality.yml"
    else:
        wf_path = workflow_path if workflow_path.is_absolute() else root / workflow_path

    # --- Build workflow YAML ---
    workflow_yaml = WORKFLOW_TEMPLATE.format(min_score=min_score)

    # --- Dry run ---
    if dry_run:
        console.print("[bold cyan]--- agentkit-quality.yml (dry run) ---[/bold cyan]")
        console.print(workflow_yaml)
        console.print("[dim]Dry run: no files written.[/dim]")
        return

    # --- GitHub detection ---
    if not _is_github_repo(root):
        console.print(
            "[yellow]Warning:[/yellow] No GitHub remote detected. "
            "Workflow will be written but may need manual adjustment for your CI provider."
        )

    # --- Write workflow ---
    if wf_path.exists() and not force:
        console.print(
            f"[yellow]Skipped:[/yellow] {wf_path} already exists. "
            "Use [bold]--force[/bold] to overwrite."
        )
        workflow_written = False
    else:
        wf_path.parent.mkdir(parents=True, exist_ok=True)
        wf_path.write_text(workflow_yaml, encoding="utf-8")
        action = "Overwrote" if wf_path.exists() else "Created"
        console.print(f"[green]✓[/green] {action} workflow: [bold]{wf_path.relative_to(root)}[/bold]")
        workflow_written = True

    # --- Baseline generation ---
    baseline_path = root / ".agentkit-baseline.json"
    baseline_written = False
    if skip_baseline:
        console.print("[dim]Skipped baseline generation (--skip-baseline).[/dim]")
    else:
        console.print("\n[dim]Generating baseline report...[/dim]")
        ok = _run_baseline(root)
        if ok and baseline_path.exists():
            console.print(f"[green]✓[/green] Baseline saved to [bold].agentkit-baseline.json[/bold]")
            console.print(
                "[dim]Commit .agentkit-baseline.json alongside the workflow so CI can use "
                "--baseline-report for regression detection.[/dim]"
            )
            baseline_written = True
        else:
            console.print(
                "[yellow]Warning:[/yellow] Baseline generation failed or produced no output. "
                "You can generate it later with: [bold]agentkit report --json --output .agentkit-baseline.json[/bold]"
            )

    # --- Badge injection ---
    badge_result = False
    if no_badge:
        console.print("[dim]Skipped badge injection (--no-badge).[/dim]")
    else:
        badge_result = _inject_badge(root)
        if badge_result:
            console.print("[green]✓[/green] Badge injected into [bold]README.md[/bold]")
        else:
            console.print("[dim]Badge injection skipped (no README.md or injection failed).[/dim]")

    # --- Summary ---
    lines = ["", "[bold]agentkit setup-ci complete![/bold]", ""]
    if workflow_written:
        lines.append(f"  • Workflow written: [cyan]{wf_path.relative_to(root)}[/cyan]")
    if baseline_written:
        lines.append("  • Baseline saved:   [cyan].agentkit-baseline.json[/cyan]")
    if badge_result:
        lines.append("  • Badge injected:   [cyan]README.md[/cyan]")
    lines += [
        "",
        "Next steps:",
        "  1. [bold]git add .github/workflows/agentkit-quality.yml .agentkit-baseline.json README.md[/bold]",
        "  2. [bold]git commit -m 'ci: add agentkit quality workflow'[/bold]",
        "  3. Push to GitHub — CI will run on every push and PR.",
        "  4. (Optional) Add local quality gates: [bold]agentkit hooks install[/bold]",
    ]

    console.print(Panel("\n".join(lines), border_style="green"))
