#!/usr/bin/env python3
"""Generate OCI Terraform provider resource reference from provider schema."""
import json, sys, subprocess, os

def main():
    schema_dir = "/tmp/tf_schema"
    os.makedirs(schema_dir, exist_ok=True)

    # Write minimal tf config
    with open(f"{schema_dir}/main.tf", "w") as f:
        f.write('terraform {\n  required_providers {\n    oci = {\n      source = "oracle/oci"\n    }\n  }\n}\n')

    # Init
    subprocess.run(["terraform", f"-chdir={schema_dir}", "init", "-input=false", "-no-color"],
                   capture_output=True, timeout=120)

    # Get schema
    result = subprocess.run(["terraform", f"-chdir={schema_dir}", "providers", "schema", "-json"],
                           capture_output=True, text=True, timeout=60)
    data = json.loads(result.stdout)

    oci = data["provider_schemas"].get("registry.terraform.io/oracle/oci", {})
    res = oci.get("resource_schemas", {})
    ds = oci.get("data_source_schemas", {})

    important_prefixes = [
        "oci_core_", "oci_network_firewall_", "oci_network_load_balancer_",
        "oci_load_balancer_", "oci_database_", "oci_identity_",
        "oci_objectstorage_", "oci_containerengine_", "oci_functions_",
        "oci_dns_", "oci_file_storage_", "oci_kms_", "oci_vault_",
        "oci_bastion_", "oci_waf_", "oci_certificates_",
    ]

    lines = []
    lines.append("# OCI Terraform Provider — Resource Reference")
    lines.append(f"# Total: {len(res)} resources, {len(ds)} data sources")
    lines.append("")

    for prefix in important_prefixes:
        cat_resources = {k: v for k, v in sorted(res.items()) if k.startswith(prefix)}
        if not cat_resources:
            continue
        cat_name = prefix.rstrip("_").replace("oci_", "").replace("_", " ").title()
        lines.append(f"## {cat_name}")
        for rname, rschema in cat_resources.items():
            attrs = rschema.get("block", {}).get("attributes", {})
            required = [a for a, v in attrs.items() if v.get("required")]
            block_types = list(rschema.get("block", {}).get("block_types", {}).keys())
            parts = [f"- **{rname}**"]
            if required:
                parts.append(f"  required: {', '.join(required)}")
            if block_types:
                parts.append(f"  blocks: {', '.join(block_types)}")
            lines.append("".join(parts))
        lines.append("")

    # Also generate a flat list of ALL resource names for quick lookup
    lines.append("## All Resource Types (full list)")
    for rname in sorted(res.keys()):
        lines.append(f"- {rname}")

    output = "/data/oci_tf_resource_reference.txt"
    with open(output, "w") as f:
        f.write("\n".join(lines))

    print(f"Generated {len(lines)} lines -> {output}")
    print(f"Resources: {len(res)}, Data Sources: {len(ds)}")

if __name__ == "__main__":
    main()
