#!/usr/bin/env python3
"""Generate _changelog.py from git tags.

Run before building the wheel to embed changelog data in the package.
Produces src/styrened/_changelog.py with a list of (version, summary) tuples.
"""

import subprocess
import sys
from pathlib import Path


def main() -> None:
    repo_root = Path(__file__).resolve().parent.parent
    output = repo_root / "src" / "styrened" / "_changelog.py"

    # Get all version tags sorted by version
    result = subprocess.run(
        ["git", "tag", "--list", "v*", "--sort=version:refname"],
        capture_output=True,
        text=True,
        cwd=str(repo_root),
    )
    if result.returncode != 0:
        print(f"git tag failed: {result.stderr}", file=sys.stderr)
        sys.exit(1)

    tags = [t.strip() for t in result.stdout.strip().splitlines() if t.strip()]

    entries: list[tuple[str, str]] = []

    for i, tag in enumerate(tags):
        version = tag.lstrip("v")

        # Get commits between previous tag and this tag
        if i == 0:
            # First tag — get its commit message
            prev = f"{tag}~1"
        else:
            prev = tags[i - 1]

        commit_result = subprocess.run(
            ["git", "log", f"{prev}..{tag}", "--oneline", "--no-merges"],
            capture_output=True,
            text=True,
            cwd=str(repo_root),
        )

        if commit_result.returncode != 0:
            continue

        # Collect non-bump commit summaries
        summaries = []
        for line in commit_result.stdout.strip().splitlines():
            if " " not in line:
                continue
            summary = line.split(" ", 1)[1].strip()
            if not summary or "bump version" in summary.lower():
                continue
            summaries.append(summary)

        # Use first meaningful commit as the version summary
        combined = "; ".join(summaries) if summaries else ""
        entries.append((version, combined))

    # Write the module
    lines = [
        "# Auto-generated by scripts/generate_changelog.py",
        "# Do not edit manually.",
        "ENTRIES: list[tuple[str, str]] = [",
    ]
    for version, summary in entries:
        # Escape quotes in summary
        safe = summary.replace("\\", "\\\\").replace('"', '\\"')
        lines.append(f'    ("{version}", "{safe}"),')
    lines.append("]")
    lines.append("")

    output.write_text("\n".join(lines))
    print(f"Generated {output} with {len(entries)} entries")


if __name__ == "__main__":
    main()
