"""Analyzer entry point: given a new + previous build, produce a Markdown report.

Source of API surface (Phase 1.5+): Blizzard's auto-generated API docs in
`Interface/AddOns/Blizzard_APIDocumentationGenerated/` on Gethe/wow-ui-source.
We diff the per-build trees by SHA and only fetch files whose contents
changed, then extract function names and event LiteralNames from each
changed file. See `bot/lib/apidocs.py`.

Tags on Gethe/wow-ui-source are bare retail version strings ("12.0.5",
"11.2.7"). Classic flavors are not yet covered upstream.
"""
import argparse
from pathlib import Path

from bot.lib.apidocs import diff_api_surface
from bot.lib.diff import Diff, compute_diff
from bot.lib.grep import find_call_sites
from bot.lib.report import render


def _tag_for(branch: str, version: str) -> str:
    # `branch` is unused in Phase 1.5 but kept in the signature so a future
    # phase can route classic_era/classic to a different upstream repo.
    del branch
    return version


def run(
    *,
    branch: str,
    new_version: str,
    new_build: int,
    previous_version: str,
    previous_build: int,
    repo_root: Path,
    reports_dir: Path,
    detected_at: str,
) -> tuple[int, Path, set[str]]:
    old_tag = _tag_for(branch, previous_version)
    new_tag = _tag_for(branch, new_version)

    try:
        removed_syms, added_syms = diff_api_surface(old_tag, new_tag)
    except Exception as exc:
        # Surface as an empty diff so the pipeline still produces a (zero
        # at-risk) report rather than crashing the detector.
        print(f"apidocs.diff_api_surface failed for {old_tag}->{new_tag}: {exc}")
        removed_syms, added_syms = set(), set()

    # Reuse compute_diff to apply the rename heuristic over the delta sets.
    diff: Diff = compute_diff(removed_syms, added_syms)
    sites = find_call_sites(diff.removed, repo_root)

    md = render(
        branch=branch,
        new_version=new_version,
        new_build=new_build,
        previous_version=previous_version,
        previous_build=previous_build,
        detected_at=detected_at,
        diff=diff,
        sites=sites,
    )
    slug = new_version.replace(".", "_")
    out = reports_dir / f"{detected_at[:10]}-build-{new_build}-{slug}.md"
    out.write_text(md, encoding="utf-8")
    return len(sites), out, set(diff.removed)


def _cli() -> int:
    p = argparse.ArgumentParser()
    p.add_argument("--branch", required=True)
    p.add_argument("--new-version", required=True)
    p.add_argument("--new-build", type=int, required=True)
    p.add_argument("--previous-version", required=True)
    p.add_argument("--previous-build", type=int, required=True)
    p.add_argument("--repo-root", required=True)
    p.add_argument("--reports-dir", required=True)
    p.add_argument("--detected-at", required=True)
    args = p.parse_args()

    count, path, _removed = run(
        branch=args.branch,
        new_version=args.new_version,
        new_build=args.new_build,
        previous_version=args.previous_version,
        previous_build=args.previous_build,
        repo_root=Path(args.repo_root),
        reports_dir=Path(args.reports_dir),
        detected_at=args.detected_at,
    )
    print(path)
    return 0 if count == 0 else 1


if __name__ == "__main__":
    raise SystemExit(_cli())
