"""Cloud resource type definitions for the Resource Registry.

Contains generic cloud base types, AWS provider types, and GCP/Azure
placeholders.  Extracted from ``_resource_registry_data.py``.

.. note::

    This module is 754 lines, exceeding the 500-line CONTRIBUTING
    guideline.  The overage is accepted because splitting the 36 AWS
    type definitions mid-file would break the ``_aws_type()`` helper
    pattern.  A follow-up extraction to ``_resource_registry_cloud_aws``
    is tracked but not blocking.
"""

from __future__ import annotations

from typing import Any

__all__ = ["AWS_TYPES", "CLOUD_BASE_TYPES", "GCP_AZURE_TYPES"]

# ---------------------------------------------------------------------------
# Shared constants
# ---------------------------------------------------------------------------

_CLOUD_HANDLER = "cleveragents.resource.handlers.cloud:CloudResourceHandler"
_CLOUD_CAPS_RW: dict[str, bool] = {
    "read": True,
    "write": True,
    "sandbox": False,
    "checkpoint": False,
}
_CLOUD_CAPS_RO: dict[str, bool] = {
    "read": True,
    "write": False,
    "sandbox": False,
    "checkpoint": False,
}


def _cloud_base(
    name: str,
    description: str,
    *,
    child_types: list[str] | None = None,
) -> dict[str, Any]:
    """Return a generic ``cloud-*`` abstract base type definition."""
    return {
        "name": name,
        "description": description,
        "resource_kind": "physical",
        "sandbox_strategy": "none",
        "user_addable": False,
        "built_in": True,
        "cli_args": [],
        "parent_types": [],
        "child_types": child_types or [],
        "handler": _CLOUD_HANDLER,
        "capabilities": dict(_CLOUD_CAPS_RO),
    }


def _aws_type(
    name: str,
    description: str,
    *,
    inherits: str | None = None,
    parent_types: list[str] | None = None,
    child_types: list[str] | None = None,
    cli_args: list[dict[str, Any]] | None = None,
    user_addable: bool = False,
    capabilities: dict[str, bool] | None = None,
) -> dict[str, Any]:
    """Return an ``aws-*`` provider-specific type definition."""
    d: dict[str, Any] = {
        "name": name,
        "description": description,
        "resource_kind": "physical",
        "sandbox_strategy": "none",
        "user_addable": user_addable,
        "built_in": True,
        "cli_args": cli_args or [],
        "parent_types": parent_types or [],
        "child_types": child_types or [],
        "handler": _CLOUD_HANDLER,
        "capabilities": dict(capabilities or _CLOUD_CAPS_RO),
    }
    if inherits is not None:
        d["inherits"] = inherits
    return d


# ---------------------------------------------------------------------------
# Built-in resource type definitions (registered at startup)
# ---------------------------------------------------------------------------

# IMPORTANT: Order matters — children must appear after their parents so
# that ``bootstrap_builtin_types()`` can resolve ``inherits`` references.

# ===== Git / Filesystem / Container types (unchanged) =====

_GIT_FS_CONTAINER_TYPES: list[dict[str, Any]] = [
    {
        "name": "git-checkout",
        "description": "A local git checkout (cloned repository or worktree).",
        "resource_kind": "physical",
        "sandbox_strategy": "git_worktree",
        "user_addable": True,
        "built_in": True,
        "cli_args": [
            {
                "name": "path",
                "type": "path",
                "required": True,
                "description": "Path to the git checkout directory.",
            },
            {
                "name": "branch",
                "type": "string",
                "required": False,
                "description": "Branch to use (defaults to current HEAD).",
                "default": None,
            },
        ],
        "parent_types": [],
        "child_types": [
            "git",
            "fs-directory",
            "fs-file",
            "devcontainer-instance",
            "devcontainer-file",
        ],
        "handler": "cleveragents.resource.handlers.git_checkout:GitCheckoutHandler",
        "capabilities": {
            "read": True,
            "write": True,
            "sandbox": True,
            "checkpoint": True,
        },
    },
    {
        "name": "fs-directory",
        "description": "A local filesystem directory.",
        "resource_kind": "physical",
        "sandbox_strategy": "copy_on_write",
        "user_addable": True,
        "built_in": True,
        "cli_args": [
            {
                "name": "path",
                "type": "path",
                "required": True,
                "description": "Path to the directory.",
            },
        ],
        "parent_types": ["git-checkout", "fs-directory"],
        "child_types": [
            "fs-directory",
            "fs-file",
            "fs-symlink",
            "fs-hardlink",
            "devcontainer-instance",
            "devcontainer-file",
        ],
        "auto_discovery": {
            "enabled": True,
            "scan_depth": 1,
            "rules": [
                {"type": "fs-directory", "pattern": "*/"},
                {"type": "fs-file", "pattern": "*"},
                {"type": "fs-symlink", "pattern": "symlink:*"},
                {"type": "fs-hardlink", "pattern": "hardlink:*"},
            ],
        },
        "handler": "cleveragents.resource.handlers.fs_directory:FsDirectoryHandler",
        "capabilities": {
            "read": True,
            "write": True,
            "sandbox": True,
            "checkpoint": False,
        },
    },
    {
        "name": "container-instance",
        "description": "A container execution environment instance.",
        "resource_kind": "physical",
        "sandbox_strategy": "snapshot",
        "user_addable": True,
        "built_in": True,
        "cli_args": [
            {
                "name": "image",
                "type": "string",
                "required": False,
                "description": "Container image reference.",
                "default": None,
            },
        ],
        "parent_types": ["git-checkout", "fs-directory"],
        "child_types": [],
        "handler": ("cleveragents.resource.handlers.devcontainer:DevcontainerHandler"),
        "capabilities": {
            "read": True,
            "write": True,
            "sandbox": True,
            "checkpoint": False,
        },
    },
    {
        "name": "devcontainer-instance",
        "description": (
            "A devcontainer execution environment auto-discovered "
            "from .devcontainer/ configuration."
        ),
        "resource_kind": "physical",
        "sandbox_strategy": "snapshot",
        "user_addable": True,
        "built_in": True,
        "inherits": "container-instance",
        "cli_args": [
            {
                "name": "path",
                "type": "path",
                "required": True,
                "description": (
                    "Path to the directory containing .devcontainer/devcontainer.json."
                ),
            },
        ],
        "parent_types": ["git-checkout", "fs-directory"],
        "child_types": ["devcontainer-file"],
        "auto_discovery": {
            "trigger_types": ["git-checkout", "fs-directory"],
            "scan_paths": [
                ".devcontainer/devcontainer.json",
                ".devcontainer.json",
            ],
        },
        "handler": ("cleveragents.resource.handlers.devcontainer:DevcontainerHandler"),
        "capabilities": {
            "read": True,
            "write": True,
            "sandbox": True,
            "checkpoint": False,
        },
    },
    {
        "name": "devcontainer-file",
        "description": "A single devcontainer.json configuration file resource.",
        "resource_kind": "physical",
        "sandbox_strategy": "copy_on_write",
        "user_addable": False,
        "built_in": True,
        "cli_args": [],
        "parent_types": ["devcontainer-instance"],
        "child_types": [],
        "handler": ("cleveragents.resource.handlers.devcontainer:DevcontainerHandler"),
        "capabilities": {
            "read": True,
            "write": False,
            "sandbox": False,
            "checkpoint": False,
        },
    },
]


# ===== Generic cloud base types (provider-agnostic) =====
#
# Abstract base types that define common cloud concepts.  Provider-
# specific types (``aws-*``, ``azure-*``, etc.) inherit from these.
# Not user-addable — users create provider-specific account types.

CLOUD_BASE_TYPES: list[dict[str, Any]] = [
    # -- Account & region structure --
    _cloud_base(
        "cloud-account",
        "Abstract base: a cloud provider account or subscription.",
    ),
    _cloud_base(
        "cloud-region",
        "Abstract base: a geographic region within a cloud account.",
    ),
    # -- Networking --
    _cloud_base(
        "cloud-network",
        "Abstract base: a virtual network (VPC, VNet, etc.).",
    ),
    _cloud_base(
        "cloud-subnet",
        "Abstract base: a subnet within a virtual network.",
    ),
    _cloud_base(
        "cloud-security-group",
        "Abstract base: network security rules / firewall group.",
    ),
    _cloud_base(
        "cloud-load-balancer",
        "Abstract base: a network load balancer.",
    ),
    # -- Compute --
    _cloud_base(
        "cloud-compute-instance",
        "Abstract base: a virtual machine or compute instance.",
    ),
    # -- Storage --
    _cloud_base(
        "cloud-object-store",
        "Abstract base: object / blob storage bucket.",
    ),
    _cloud_base(
        "cloud-block-storage",
        "Abstract base: block storage volume.",
    ),
    # -- IAM --
    _cloud_base(
        "cloud-identity-principal",
        "Abstract base: IAM user or service principal.",
    ),
    _cloud_base(
        "cloud-role",
        "Abstract base: IAM role.",
    ),
    _cloud_base(
        "cloud-policy",
        "Abstract base: IAM or access policy document.",
    ),
    # -- Observability --
    _cloud_base(
        "cloud-log-group",
        "Abstract base: log aggregation group.",
    ),
    _cloud_base(
        "cloud-alarm",
        "Abstract base: monitoring alarm or alert.",
    ),
    # -- Messaging --
    _cloud_base(
        "cloud-queue",
        "Abstract base: message queue.",
    ),
    _cloud_base(
        "cloud-topic",
        "Abstract base: pub/sub notification topic.",
    ),
    # -- Containers --
    _cloud_base(
        "cloud-container-repo",
        "Abstract base: container image registry / repository.",
    ),
    _cloud_base(
        "cloud-container-cluster",
        "Abstract base: container orchestration cluster.",
    ),
    _cloud_base(
        "cloud-container-service",
        "Abstract base: container workload / service.",
    ),
]


# ===== AWS provider types =====
#
# Full AWS hierarchy inheriting from ``cloud-*`` generic bases.
# Only ``aws-account`` is user-addable (top-level entry point with
# credential CLI args).  All other AWS types are children discovered
# or created within the account/region/VPC hierarchy.

AWS_TYPES: list[dict[str, Any]] = [
    # -- Account & region --
    _aws_type(
        "aws-account",
        "An Amazon Web Services account with credential configuration.",
        inherits="cloud-account",
        user_addable=True,
        cli_args=[
            {
                "name": "access-key-id",
                "type": "string",
                "required": False,
                "description": "AWS access key ID.",
            },
            {
                "name": "secret-access-key",
                "type": "string",
                "required": False,
                "description": "AWS secret access key.",
            },
            {
                "name": "session-token",
                "type": "string",
                "required": False,
                "description": (
                    "AWS session token (optional, for temporary credentials)."
                ),
            },
            {
                "name": "region",
                "type": "string",
                "required": False,
                "description": "Default AWS region (e.g. us-east-1).",
            },
            {
                "name": "profile",
                "type": "string",
                "required": False,
                "description": "AWS profile name from ~/.aws/credentials.",
            },
        ],
        child_types=[
            "aws-region",
            "aws-iam-user",
            "aws-iam-role",
            "aws-iam-policy",
            "aws-iam-instance-profile",
        ],
        capabilities=_CLOUD_CAPS_RW,
    ),
    _aws_type(
        "aws-region",
        "An AWS geographic region (e.g. us-east-1).",
        inherits="cloud-region",
        parent_types=["aws-account"],
        child_types=[
            "aws-vpc",
            "aws-ec2-instance",
            "aws-ami",
            "aws-launch-template",
            "aws-asg",
            "aws-s3-bucket",
            "aws-ebs-volume",
            "aws-efs-filesystem",
            "aws-cloudwatch-log-group",
            "aws-cloudwatch-alarm",
            "aws-cloudwatch-metric",
            "aws-eventbridge-bus",
            "aws-sqs-queue",
            "aws-sns-topic",
            "aws-ecr-repo",
            "aws-ecs-cluster",
            "aws-ecs-task-def",
            "aws-eks-cluster",
        ],
    ),
    # -- Networking --
    _aws_type(
        "aws-vpc",
        "An AWS Virtual Private Cloud network.",
        inherits="cloud-network",
        parent_types=["aws-region"],
        child_types=[
            "aws-subnet",
            "aws-igw",
            "aws-nat-gw",
            "aws-route-table",
            "aws-nacl",
            "aws-security-group",
            "aws-alb",
            "aws-nlb",
            "aws-target-group",
        ],
    ),
    _aws_type(
        "aws-subnet",
        "A subnet within an AWS VPC.",
        inherits="cloud-subnet",
        parent_types=["aws-vpc"],
        child_types=["aws-ec2-instance", "aws-nat-gw"],
    ),
    _aws_type(
        "aws-igw",
        "An AWS Internet Gateway attached to a VPC.",
        parent_types=["aws-vpc"],
    ),
    _aws_type(
        "aws-nat-gw",
        "An AWS NAT Gateway in a subnet.",
        parent_types=["aws-subnet", "aws-vpc"],
    ),
    _aws_type(
        "aws-route-table",
        "An AWS VPC route table.",
        parent_types=["aws-vpc"],
    ),
    _aws_type(
        "aws-nacl",
        "An AWS Network Access Control List.",
        parent_types=["aws-vpc"],
    ),
    _aws_type(
        "aws-security-group",
        "An AWS security group (stateful firewall rules).",
        inherits="cloud-security-group",
        parent_types=["aws-vpc"],
    ),
    _aws_type(
        "aws-alb",
        "An AWS Application Load Balancer.",
        inherits="cloud-load-balancer",
        parent_types=["aws-vpc"],
        child_types=["aws-listener"],
    ),
    _aws_type(
        "aws-nlb",
        "An AWS Network Load Balancer.",
        inherits="cloud-load-balancer",
        parent_types=["aws-vpc"],
        child_types=["aws-listener"],
    ),
    _aws_type(
        "aws-target-group",
        "An AWS load balancer target group.",
        parent_types=["aws-vpc"],
    ),
    _aws_type(
        "aws-listener",
        "An AWS load balancer listener rule.",
        parent_types=["aws-alb", "aws-nlb"],
    ),
    # -- Compute --
    _aws_type(
        "aws-ec2-instance",
        "An AWS EC2 virtual machine instance.",
        inherits="cloud-compute-instance",
        parent_types=["aws-subnet", "aws-region"],
    ),
    _aws_type(
        "aws-ami",
        "An AWS Amazon Machine Image.",
        parent_types=["aws-region"],
    ),
    _aws_type(
        "aws-launch-template",
        "An AWS EC2 launch template.",
        parent_types=["aws-region"],
    ),
    _aws_type(
        "aws-asg",
        "An AWS Auto Scaling Group.",
        parent_types=["aws-region"],
    ),
    # -- Storage --
    _aws_type(
        "aws-s3-bucket",
        "An AWS S3 object storage bucket.",
        inherits="cloud-object-store",
        parent_types=["aws-region"],
    ),
    _aws_type(
        "aws-ebs-volume",
        "An AWS Elastic Block Store volume.",
        inherits="cloud-block-storage",
        parent_types=["aws-region"],
    ),
    _aws_type(
        "aws-efs-filesystem",
        "An AWS Elastic File System.",
        parent_types=["aws-region"],
    ),
    # -- IAM --
    _aws_type(
        "aws-iam-user",
        "An AWS IAM user.",
        inherits="cloud-identity-principal",
        parent_types=["aws-account"],
    ),
    _aws_type(
        "aws-iam-role",
        "An AWS IAM role.",
        inherits="cloud-role",
        parent_types=["aws-account"],
    ),
    _aws_type(
        "aws-iam-policy",
        "An AWS IAM managed policy.",
        inherits="cloud-policy",
        parent_types=["aws-account"],
    ),
    _aws_type(
        "aws-iam-instance-profile",
        "An AWS IAM instance profile (role wrapper for EC2).",
        parent_types=["aws-account"],
    ),
    # -- Observability --
    _aws_type(
        "aws-cloudwatch-log-group",
        "An AWS CloudWatch Logs log group.",
        inherits="cloud-log-group",
        parent_types=["aws-region"],
    ),
    _aws_type(
        "aws-cloudwatch-alarm",
        "An AWS CloudWatch alarm.",
        inherits="cloud-alarm",
        parent_types=["aws-region"],
    ),
    _aws_type(
        "aws-cloudwatch-metric",
        "An AWS CloudWatch custom or service metric.",
        parent_types=["aws-region"],
    ),
    _aws_type(
        "aws-eventbridge-bus",
        "An AWS EventBridge event bus.",
        parent_types=["aws-region"],
        child_types=["aws-eventbridge-rule"],
    ),
    _aws_type(
        "aws-eventbridge-rule",
        "An AWS EventBridge rule.",
        parent_types=["aws-eventbridge-bus"],
        child_types=["aws-eventbridge-target"],
    ),
    _aws_type(
        "aws-eventbridge-target",
        "An AWS EventBridge rule target.",
        parent_types=["aws-eventbridge-rule"],
    ),
    # -- Messaging --
    _aws_type(
        "aws-sqs-queue",
        "An AWS SQS message queue.",
        inherits="cloud-queue",
        parent_types=["aws-region"],
    ),
    _aws_type(
        "aws-sns-topic",
        "An AWS SNS notification topic.",
        inherits="cloud-topic",
        parent_types=["aws-region"],
        child_types=["aws-sns-subscription"],
    ),
    _aws_type(
        "aws-sns-subscription",
        "An AWS SNS topic subscription.",
        parent_types=["aws-sns-topic"],
    ),
    # -- Containers --
    _aws_type(
        "aws-ecr-repo",
        "An AWS Elastic Container Registry repository.",
        inherits="cloud-container-repo",
        parent_types=["aws-region"],
    ),
    _aws_type(
        "aws-ecs-cluster",
        "An AWS Elastic Container Service cluster.",
        inherits="cloud-container-cluster",
        parent_types=["aws-region"],
        child_types=["aws-ecs-service"],
    ),
    _aws_type(
        "aws-ecs-service",
        "An AWS ECS service (running task instances).",
        inherits="cloud-container-service",
        parent_types=["aws-ecs-cluster"],
    ),
    _aws_type(
        "aws-ecs-task-def",
        "An AWS ECS task definition.",
        parent_types=["aws-region"],
    ),
    _aws_type(
        "aws-eks-cluster",
        "An AWS Elastic Kubernetes Service cluster.",
        inherits="cloud-container-cluster",
        parent_types=["aws-region"],
        child_types=["aws-eks-nodegroup"],
    ),
    _aws_type(
        "aws-eks-nodegroup",
        "An AWS EKS managed node group.",
        parent_types=["aws-eks-cluster"],
    ),
]


# ===== GCP / Azure placeholders =====
#
# Flat provider-level types kept for forward compatibility.  Full
# hierarchies for these providers are deferred to future PRs.

GCP_AZURE_TYPES: list[dict[str, Any]] = [
    {
        "name": "gcp",
        "description": "Google Cloud Platform resource (hierarchy pending).",
        "resource_kind": "physical",
        "sandbox_strategy": "none",
        "user_addable": True,
        "built_in": True,
        "inherits": "cloud-account",
        "cli_args": [
            {
                "name": "service-account-json-path",
                "type": "string",
                "required": False,
                "description": "Path to GCP service account JSON key file.",
            },
            {
                "name": "project-id",
                "type": "string",
                "required": False,
                "description": "GCP project ID.",
            },
            {
                "name": "region",
                "type": "string",
                "required": False,
                "description": "GCP region (e.g. us-central1).",
            },
        ],
        "parent_types": [],
        "child_types": [],
        "handler": _CLOUD_HANDLER,
        "capabilities": dict(_CLOUD_CAPS_RW),
    },
    {
        "name": "azure",
        "description": "Microsoft Azure cloud resource (hierarchy pending).",
        "resource_kind": "physical",
        "sandbox_strategy": "none",
        "user_addable": True,
        "built_in": True,
        "inherits": "cloud-account",
        "cli_args": [
            {
                "name": "subscription-id",
                "type": "string",
                "required": False,
                "description": "Azure subscription ID.",
            },
            {
                "name": "tenant-id",
                "type": "string",
                "required": False,
                "description": "Azure Active Directory tenant ID.",
            },
            {
                "name": "client-id",
                "type": "string",
                "required": False,
                "description": "Azure service principal client ID.",
            },
            {
                "name": "client-secret",
                "type": "string",
                "required": False,
                "description": "Azure service principal client secret.",
            },
            {
                "name": "region",
                "type": "string",
                "required": False,
                "description": "Azure region (e.g. eastus).",
            },
        ],
        "parent_types": [],
        "child_types": [],
        "handler": _CLOUD_HANDLER,
        "capabilities": dict(_CLOUD_CAPS_RW),
    },
]
