#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "boto3",
#     "requests",
# ]
# ///
"""
Fetch resource types from undocumented AWS Resource Groups Tagging API endpoint.

This endpoint returns the full list of resource types supported by the tagging API.
"""

import json

import boto3
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
import requests


def fetch_resource_types_page(
    query_type: str,
    region: str,
    credentials,
    next_token: str | None = None,
) -> dict:
    """Fetch a single page of resource types."""
    url = f"https://resource-groups.{region}.amazonaws.com/resource-types-list"

    headers = {"Content-Type": "application/json"}
    payload = {"QueryType": query_type, "MaxResults": 50}
    if next_token:
        payload["NextToken"] = next_token

    body = json.dumps(payload)

    request = AWSRequest(method="POST", url=url, headers=headers, data=body)
    SigV4Auth(credentials, "resource-groups", region).add_auth(request)

    response = requests.post(url, headers=dict(request.headers), data=body)
    response.raise_for_status()

    return response.json()


def fetch_resource_types(
    query_type,
    region="us-east-1",
) -> list[str]:
    """
    Fetch all resource types with pagination.

    Args:
        query_type: CLOUDFORMATION_STACK_1_0 or TAG_FILTERS_1_0
        region: AWS region to query

    Returns:
        List of resource type strings
    """
    session = boto3.Session()
    credentials = session.get_credentials()

    resource_types = []
    next_token = None

    while True:
        data = fetch_resource_types_page(query_type, region, credentials, next_token)
        resource_types.extend(data.get("ResourceTypes", []))

        next_token = data.get("NextToken")
        if not next_token:
            break

    return resource_types


def main():
    resource_types = fetch_resource_types(query_type="TAG_FILTERS_1_0")
    resource_types = list(sorted(set(resource_types)))
    # resource_types = fetch_resource_types(query_type="CLOUDFORMATION_STACK_1_0")
    with open("tagging_resource.json", "w") as f:
        json.dump(resource_types, f, indent=2)


if __name__ == "__main__":
    main()
