#!/usr/bin/env python3
"""Generate a human-readable sync report from discovery and upstream check results."""
from __future__ import annotations

import argparse
import json
import os
import sys
from datetime import datetime
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]


def main() -> None:
    parser = argparse.ArgumentParser(description="Generate sync report.")
    parser.add_argument("--discovery", default="docs/sources/reports/discovery.json")
    parser.add_argument("--upstream", default="docs/sources/reports/upstream-check.json")
    parser.add_argument("--output", default="docs/sources/reports/sync-report.md")
    args = parser.parse_args()
    
    discovery_path = REPO_ROOT / args.discovery
    upstream_path = REPO_ROOT / args.upstream
    output_path = REPO_ROOT / args.output
    
    # Load data
    discovery = {}
    if discovery_path.exists():
        discovery = json.loads(discovery_path.read_text(encoding="utf-8"))
    
    upstream = {}
    if upstream_path.exists():
        upstream = json.loads(upstream_path.read_text(encoding="utf-8"))
    
    new_skills = discovery.get("discoveries", [])
    upstream_updates = [r for r in upstream.get("rows", []) if r.get("needs_update")]
    
    has_updates = bool(new_skills or upstream_updates)
    
    # Set GitHub Actions output
    github_output = os.environ.get("GITHUB_OUTPUT")
    if github_output:
        with open(github_output, "a") as f:
            f.write(f"has_updates={'true' if has_updates else 'false'}\n")
    
    # Generate report
    lines = [
        f"# Weekly Skill Sync Report",
        f"",
        f"**Generated**: {datetime.utcnow().strftime('%Y-%m-%d %H:%M UTC')}",
        f"**Local skills**: {discovery.get('local_skill_count', 'N/A')}",
        f"",
    ]
    
    if new_skills:
        lines.append(f"## New Skills Discovered ({len(new_skills)})")
        lines.append("")
        lines.append("| Skill | Source Repo | Stars | Description |")
        lines.append("|-------|-----------|-------|-------------|")
        for s in new_skills[:30]:  # Cap at 30
            name = s.get("name", "")
            repo = s.get("source_repo", "")
            stars = s.get("repo_stars", 0)
            desc = s.get("repo_description", "")[:80]
            lines.append(f"| `{name}` | [{repo}](https://github.com/{repo}) | {stars} | {desc} |")
        lines.append("")
    
    if upstream_updates:
        lines.append(f"## Upstream Updates ({len(upstream_updates)})")
        lines.append("")
        for u in upstream_updates:
            lines.append(f"- **{u.get('skill_name', '')}**: {u.get('update_reason', 'new commits available')}")
        lines.append("")
    
    if not has_updates:
        lines.append("No new discoveries or upstream updates this week. All skills are up to date.")
        lines.append("")
    
    lines.append("---")
    lines.append("*This report was auto-generated by the [upstream-sync workflow](.github/workflows/upstream-sync.yml).*")
    
    report = "\n".join(lines)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(report, encoding="utf-8")
    print(f"Wrote sync report: {output_path}")
    if has_updates:
        print(f"Updates found: {len(new_skills)} new skills, {len(upstream_updates)} upstream updates")
    else:
        print("No updates found.")


if __name__ == "__main__":
    main()
