"""Badge generation for GitHub README integration."""

import subprocess
import urllib.parse

import click


def get_repo_info() -> tuple[str | None, str | None]:
    """
    Get GitHub owner/repo from git remote.

    Returns:
        Tuple of (owner, repo) or (None, None) if not a git repo or not GitHub.
    """
    try:
        result = subprocess.run(
            ["git", "remote", "get-url", "origin"],
            capture_output=True,
            text=True,
            check=True,
            timeout=5,
        )
        url = result.stdout.strip()

        # Parse github.com/owner/repo
        if "github.com" in url:
            if url.startswith("git@"):
                # git@github.com:owner/repo.git
                path = url.split(":")[1].replace(".git", "")
            else:
                # https://github.com/owner/repo.git
                path = url.split("github.com/")[1].replace(".git", "")

            parts = path.split("/")
            if len(parts) >= 2:
                return parts[0], parts[1]

    except (subprocess.CalledProcessError, subprocess.TimeoutExpired, IndexError, KeyError):
        pass

    return None, None


def generate_badge_markdown_full(grade: str, score: int) -> str:
    """
    Generate complete badge markdown with instructions.

    Args:
        grade: Letter grade (A-F)
        score: Numeric score (0-100)

    Returns:
        Formatted markdown with badge and instructions.
    """
    owner, repo = get_repo_info()

    if not owner or not repo:
        return f"""
# Badge Generation

Could not detect GitHub repository.

Add this to your README.md (replace OWNER/REPO):

```markdown
[![DeepSweep Secure](https://deepsweep.ai/badge/OWNER/REPO.svg)](https://deepsweep.ai/report/OWNER/REPO)
```

Your current score: **{score}/100 (Grade {grade})**
"""

    # Grade D/F don't get badges (viral growth mechanism)
    if grade in ["D", "F"]:
        return f"""
# Badge Not Available

Your current grade is **{grade}** ({score}/100).

Fix the issues and check again to earn a badge.
Badges are available for Grade C and above (60+).

Run: deepsweep validate .
"""

    # Determine badge text based on grade
    badge_text = {"A": "Secure", "B": "Good", "C": "Checked"}.get(grade, "Checked")

    return f"""
# Add Security Badge to README

Your Grade: **{grade}** ({score}/100) ✅

## Copy this markdown to your README.md:

```markdown
[![DeepSweep {badge_text}](https://deepsweep.ai/badge/{owner}/{repo}.svg)](https://deepsweep.ai/report/{owner}/{repo})
```

## What this shows:

- **Grade A (Secure)**: Your app is secure. Ship it!
- **Grade B (Good)**: Minor things to check. Still good to go.
- **Grade C (Checked)**: Some issues, but you're on it.

The badge updates automatically when you push to main.

## Next steps:

1. Add the badge to your README.md
2. Commit and push to GitHub
3. Badge shows your security grade
4. Run deepsweep again after fixes to update it

Learn more: https://deepsweep.ai/docs/badges
"""


# Legacy functions (kept for backward compatibility)
BADGE_COLORS = {"A": "brightgreen", "B": "green", "C": "yellow", "D": "orange", "F": "red"}


def generate_badge_url(score: int, grade: str) -> str:
    """Generate shields.io badge URL (legacy)."""
    color = BADGE_COLORS.get(grade, "lightgrey")
    message = urllib.parse.quote(f"{grade} {score}/100")
    return f"https://img.shields.io/badge/DeepSweep-{message}-{color}"


def generate_markdown(score: int, grade: str) -> str:
    """Generate markdown badge (legacy)."""
    owner, repo = get_repo_info()
    if owner and repo:
        badge_text = {"A": "Secure", "B": "Good", "C": "Checked"}.get(grade, "Checked")
        return f"[![DeepSweep {badge_text}](https://deepsweep.ai/badge/{owner}/{repo}.svg)](https://deepsweep.ai/report/{owner}/{repo})"
    return f"[![DeepSweep Checked]({generate_badge_url(score, grade)})](https://deepsweep.ai)"


def generate_html(score: int, grade: str) -> str:
    """Generate HTML badge (legacy)."""
    url = generate_badge_url(score, grade)
    return f'<a href="https://deepsweep.ai"><img src="{url}" alt="Security: Checked by DeepSweep"></a>'


@click.command()
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["markdown", "html", "url", "full"]),
    default="full",
    help="Output format (full shows complete instructions)",
)
@click.option("--score", type=int, help="Security score (0-100)")
@click.option("--grade", type=str, help="Security grade (A-F)")
def badge(output_format: str, score: int | None, grade: str | None):
    """
    Generate a security badge for your repository.

    By default, shows full instructions with badge markdown.
    Use --score and --grade to override auto-detection.
    """
    # If score/grade not provided, try to get from last validation
    if score is None or grade is None:
        # Try to load from local reputation store
        try:
            from deepsweep.reputation.local_store import LocalReputationStore

            store = LocalReputationStore()
            data = store.load()

            if score is None:
                score = data.current_score if data.current_score > 0 else 100

            if grade is None:
                grade = data.last_grade if data.last_grade else "A"

        except ImportError:
            # Reputation system not available, use defaults
            score = score or 100
            grade = grade or "A"

    if output_format == "full":
        output = generate_badge_markdown_full(grade, score)
    elif output_format == "markdown":
        output = generate_markdown(score, grade)
    elif output_format == "html":
        output = generate_html(score, grade)
    else:  # url
        output = generate_badge_url(score, grade)

    click.echo(output)
