#!/usr/bin/env python3
# /// script
# requires-python = ">=3.12"
# dependencies = []
# ///
"""Map CloudFormation resources to their services."""

import json


def extract_service(resource_type: str) -> str:
    """Extract service name from AWS::<Service>::<Resource> format."""
    parts = resource_type.split("::")
    if len(parts) >= 2:
        return parts[1]
    return ""


def main():
    with open("aws_cloudformation.json") as f:
        resource_types: list[str] = json.load(f)

    # Build mapping: resource_type -> service
    resource_to_service: dict[str, str] = {}
    # Also build reverse: service -> list of resources
    service_to_resources: dict[str, list[str]] = {}

    for rt in resource_types:
        service = extract_service(rt)
        resource_to_service[rt] = service

        if service not in service_to_resources:
            service_to_resources[service] = []
        service_to_resources[service].append(rt)

    print(f"Total resources: {len(resource_to_service)}")
    print(f"Total services: {len(service_to_resources)}")

    # Save both mappings
    with open("mapping_resources.json", "w") as f:
        json.dump(resource_to_service, f, indent=2, sort_keys=True)

    with open("mapping_resources_by_service.json", "w") as f:
        json.dump(service_to_resources, f, indent=2, sort_keys=True)

    print("Saved mapping_resources.json (resource -> service)")
    print("Saved mapping_resources_by_service.json (service -> resources)")

    # Show sample
    print("\nSample by service:")
    for service in sorted(service_to_resources.keys())[:5]:
        resources = service_to_resources[service]
        print(f"  {service}: {len(resources)} resources")


if __name__ == "__main__":
    main()
