"""Generate HCL import blocks for existing cloud resources."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from complyform.core.scanner.state_parser import ResourceRecord

# Cloud-specific import ID patterns.
# Keys: resource_type → format string using resource attributes.
IMPORT_ID_PATTERNS: dict[str, str] = {
    # --- GCP ---
    "google_compute_instance": ("projects/{project}/zones/{zone}/instances/{name}"),
    "google_compute_network": "projects/{project}/global/networks/{name}",
    "google_compute_subnetwork": (
        "projects/{project}/regions/{region}/subnetworks/{name}"
    ),
    "google_compute_firewall": ("projects/{project}/global/firewalls/{name}"),
    "google_storage_bucket": "{project}/{name}",
    "google_sql_database_instance": ("projects/{project}/instances/{name}"),
    "google_kms_key_ring": ("projects/{project}/locations/{location}/keyRings/{name}"),
    "google_kms_crypto_key": "{id}",
    "google_project_iam_member": ("{project} {role} {member}"),
    "google_container_cluster": (
        "projects/{project}/locations/{location}/clusters/{name}"
    ),
    "google_logging_project_sink": "projects/{project}/sinks/{name}",
    "google_compute_ssl_policy": ("projects/{project}/global/sslPolicies/{name}"),
    "google_dns_managed_zone": ("projects/{project}/managedZones/{name}"),
    "google_bigquery_dataset": "projects/{project}/datasets/{dataset_id}",
    "google_pubsub_topic": "projects/{project}/topics/{name}",
    "google_cloudfunctions_function": (
        "projects/{project}/locations/{region}/functions/{name}"
    ),
    "google_project_service": "{project}/{service}",
    "google_service_account": ("projects/{project}/serviceAccounts/{email}"),
    "google_compute_disk": ("projects/{project}/zones/{zone}/disks/{name}"),
    "google_redis_instance": ("projects/{project}/locations/{region}/instances/{name}"),
    # --- AWS ---
    "aws_s3_bucket": "{bucket}",
    "aws_instance": "{id}",
    "aws_security_group": "{id}",
    "aws_iam_role": "{name}",
    "aws_iam_policy": "{arn}",
    "aws_iam_user": "{name}",
    "aws_vpc": "{id}",
    "aws_subnet": "{id}",
    "aws_db_instance": "{id}",
    "aws_rds_cluster": "{id}",
    "aws_lambda_function": "{function_name}",
    "aws_cloudwatch_log_group": "{name}",
    "aws_kms_key": "{key_id}",
    "aws_sns_topic": "{arn}",
    "aws_sqs_queue": "{id}",
    "aws_ecr_repository": "{name}",
    "aws_ecs_cluster": "{arn}",
    "aws_eks_cluster": "{name}",
    "aws_elasticache_cluster": "{cluster_id}",
    "aws_cloudtrail": "{name}",
    # --- Azure ---
    "azurerm_resource_group": "{id}",
    "azurerm_virtual_network": "{id}",
    "azurerm_subnet": "{id}",
    "azurerm_network_security_group": "{id}",
    "azurerm_storage_account": "{id}",
    "azurerm_key_vault": "{id}",
    "azurerm_mssql_server": "{id}",
    "azurerm_mssql_database": "{id}",
    "azurerm_cosmosdb_account": "{id}",
    "azurerm_kubernetes_cluster": "{id}",
    "azurerm_linux_virtual_machine": "{id}",
    "azurerm_windows_virtual_machine": "{id}",
    "azurerm_app_service": "{id}",
    "azurerm_function_app": "{id}",
    "azurerm_log_analytics_workspace": "{id}",
    "azurerm_monitor_diagnostic_setting": "{id}",
    "azurerm_postgresql_server": "{id}",
    "azurerm_mysql_server": "{id}",
    "azurerm_container_registry": "{id}",
    "azurerm_redis_cache": "{id}",
}


def _resolve_attr(attrs: dict[str, Any], key: str) -> str:
    """Resolve a single attribute, returning empty string if missing."""
    val = attrs.get(key)
    if val is None:
        return ""
    return str(val)


class ImportGenerator:
    """Generate HCL import blocks for existing cloud resources."""

    def generate_import_block(
        self,
        resource: ResourceRecord,
        cloud: str,
    ) -> str:
        """Generate HCL import block for a resource.

        Maps resource_type + attributes to the cloud-specific
        resource ID format.
        """
        rt = resource.resource_type
        attrs = resource.attributes
        resource_id = self._resolve_id(rt, attrs, cloud)

        return f'import {{\n  to = {resource.address}\n  id = "{resource_id}"\n}}'

    def _resolve_id(
        self,
        resource_type: str,
        attrs: dict[str, Any],
        cloud: str,
    ) -> str:
        """Resolve the import ID for a resource type."""
        pattern = IMPORT_ID_PATTERNS.get(resource_type)
        if pattern is None:
            return str(attrs.get("id", ""))

        try:
            return pattern.format_map(_AttrResolver(attrs))
        except KeyError, IndexError:
            return str(attrs.get("id", ""))


class _AttrResolver(dict[str, str]):
    """Dict-like that resolves attribute keys from resource attributes."""

    def __init__(self, attrs: dict[str, Any]) -> None:
        super().__init__()
        self._attrs = attrs

    def __missing__(self, key: str) -> str:
        val = self._attrs.get(key)
        if val is None:
            return ""
        return str(val)
