"""Generate CI/CD integration files for mirdan.

GitHub Action workflow creation was intentionally removed — mirdan is an
AI coding quality tool, not a CI system. Use pre-commit for local enforcement
and integrate mirdan's MCP server directly in your AI coding workflows.
"""

from __future__ import annotations

from importlib.resources import files
from pathlib import Path
from typing import Any


def generate_precommit_config(project_dir: Path) -> Path | None:
    """Generate .pre-commit-config.yaml from template.

    Args:
        project_dir: The project root directory.

    Returns:
        Path to the generated config, or None if already exists.
    """
    dest = project_dir / ".pre-commit-config.yaml"
    if dest.exists():
        return None  # Don't overwrite existing config

    content = _load_precommit_template()
    if content is None:
        return None

    dest.write_text(content)
    return dest


def generate_sarif_workflow(project_dir: Path) -> Path | None:
    """Generate a GitHub Action workflow that uploads SARIF results.

    Creates ``.github/workflows/mirdan-sarif.yml`` which runs mirdan
    validation and uploads results to GitHub Code Scanning.

    Args:
        project_dir: The project root directory.

    Returns:
        Path to the generated workflow, or None if already exists.
    """
    workflows_dir = project_dir / ".github" / "workflows"
    workflows_dir.mkdir(parents=True, exist_ok=True)

    dest = workflows_dir / "mirdan-sarif.yml"
    if dest.exists():
        return None

    content = _SARIF_WORKFLOW_TEMPLATE
    dest.write_text(content)
    return dest


def generate_pr_quality_check(project_dir: Path) -> Path | None:
    """Generate a GitHub Action that comments quality results on PRs.

    Args:
        project_dir: The project root directory.

    Returns:
        Path to the generated workflow, or None if already exists.
    """
    workflows_dir = project_dir / ".github" / "workflows"
    workflows_dir.mkdir(parents=True, exist_ok=True)

    dest = workflows_dir / "mirdan-pr-check.yml"
    if dest.exists():
        return None

    content = _PR_CHECK_WORKFLOW_TEMPLATE
    dest.write_text(content)
    return dest


def generate_quality_badge(score: float) -> str:
    """Generate a shields.io badge URL for a quality score.

    Args:
        score: Quality score between 0.0 and 1.0.

    Returns:
        Shields.io badge URL string.
    """
    pct = int(score * 100)
    if pct >= 90:
        color = "brightgreen"
    elif pct >= 70:
        color = "green"
    elif pct >= 50:
        color = "yellow"
    else:
        color = "red"
    return f"https://img.shields.io/badge/mirdan%20quality-{pct}%25-{color}"


def generate_pr_comment(result: dict[str, Any]) -> str:
    """Generate a markdown PR comment from a validation result.

    Args:
        result: Validation result dict.

    Returns:
        Markdown string for a PR comment.
    """
    score = result.get("score", 0.0)
    passed = result.get("passed", False)
    violations = result.get("violations", [])
    errors = [v for v in violations if v.get("severity") == "error"]
    warnings = [v for v in violations if v.get("severity") == "warning"]

    status = "PASS" if passed else "FAIL"
    emoji = "white_check_mark" if passed else "x"

    lines = [
        f"## :{emoji}: Mirdan Quality Check: {status}",
        "",
        f"**Score:** {score:.1%}",
        f"**Errors:** {len(errors)} | **Warnings:** {len(warnings)}",
        "",
    ]

    if errors:
        lines.append("### Errors")
        lines.append("")
        for v in errors[:10]:
            rule_id = v.get("rule_id", v.get("id", ""))
            msg = v.get("message", "")
            lines.append(f"- `{rule_id}`: {msg}")
        if len(errors) > 10:
            lines.append(f"- ... and {len(errors) - 10} more")
        lines.append("")

    lines.append("---")
    lines.append("*Generated by [mirdan](https://github.com/mirdan-ai/mirdan)*")

    return "\n".join(lines)


def _load_precommit_template() -> str | None:
    """Load the pre-commit config template."""
    try:
        templates_pkg = files("mirdan.integrations.templates")
        template = templates_pkg / "pre-commit-config.yml"
        return template.read_text()
    except (ModuleNotFoundError, FileNotFoundError, TypeError):
        return None


_SARIF_WORKFLOW_TEMPLATE = """\
name: Mirdan SARIF Upload
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

permissions:
  security-events: write

jobs:
  mirdan-sarif:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v5
      - run: uv tool install mirdan
      - run: mirdan export --format sarif --output results.sarif
      - uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: results.sarif
"""

_PR_CHECK_WORKFLOW_TEMPLATE = """\
name: Mirdan PR Quality Check
on:
  pull_request:
    branches: [main]

permissions:
  pull-requests: write

jobs:
  quality-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v5
      - run: uv tool install mirdan
      - run: mirdan gate
"""
