#!/usr/bin/env python3
# /// script
# requires-python = ">=3.12"
# dependencies = ["botocore"]
# ///
"""Extract tagging API operations per AWS service from botocore definitions."""

import gzip
import json
from pathlib import Path

import botocore


def get_latest_service_version(service_path: Path) -> Path | None:
    """Get the latest API version directory for a service."""
    versions = sorted(
        [d for d in service_path.iterdir() if d.is_dir()],
        reverse=True,
    )
    return versions[0] if versions else None


def load_service_definition(service_path: Path) -> dict | None:
    """Load service-2.json(.gz) from a service version directory."""
    gz_path = service_path / "service-2.json.gz"
    if gz_path.exists():
        with gzip.open(gz_path, "rt", encoding="utf-8") as f:
            return json.load(f)

    json_path = service_path / "service-2.json"
    if json_path.exists():
        with open(json_path) as f:
            return json.load(f)

    return None


def find_tag_operations(service_def: dict) -> list[str]:
    """Find operations with 'tag' in the name."""
    operations = service_def.get("operations", {})
    return sorted([name for name in operations if "Tag" in name])


def get_all_tagging_apis() -> dict[str, list[str]]:
    """Get all tagging operations for all AWS services."""
    botocore_data = Path(botocore.__path__[0]) / "data"
    results = {}

    for service_dir in sorted(botocore_data.iterdir()):
        if not service_dir.is_dir():
            continue

        version_dir = get_latest_service_version(service_dir)
        if not version_dir:
            continue

        service_def = load_service_definition(version_dir)
        if not service_def:
            continue

        tag_ops = find_tag_operations(service_def)
        if tag_ops:
            results[service_dir.name] = tag_ops

    return results


def main():
    results = get_all_tagging_apis()

    print(f"Found {len(results)} services with tag operations\n")

    # Group by operation pattern
    patterns: dict[str, list[str]] = {}
    for service, ops in results.items():
        for op in ops:
            patterns.setdefault(op, []).append(service)

    print("Operation patterns (sorted by frequency):\n")
    for op, svcs in sorted(patterns.items(), key=lambda x: -len(x[1])):
        print(f"  {op}: {len(svcs)} services")

    # Save results
    with open("tagging_apis.json", "w") as f:
        json.dump(results, f, indent=2, sort_keys=True)

    with open("tagging_apis_patterns.json", "w") as f:
        json.dump(
            {k: sorted(v) for k, v in sorted(patterns.items())},
            f,
            indent=2,
        )

    print(f"\nSaved to tagging_apis.json and tagging_patterns.json")


if __name__ == "__main__":
    main()
