"""ACDL tagging standard custom Checkov rule (D-054).

Checks that all taggable AWS resources have the required ACDL tags:
  acdl:owner, acdl:contract, acdl:environment, acdl:cost-center

Fails (severity medium) when any required tag is missing.
Closes the D-043 deferral (the SKIPPED ACDL_TAG_NAMING placeholder
becomes a real check).
"""

from __future__ import annotations

from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck
from checkov.common.models.enums import CheckResult, CheckCategories

REQUIRED_TAGS = ("acdl:owner", "acdl:contract", "acdl:environment", "acdl:cost-center")

# Resources that support tags (exclude resources that have no tags attribute)
NON_TAGGABLE_TYPES = (
    "aws_cloudfront_origin_access_control",
    "aws_lambda_function_url",
    "aws_route_table_association",
    "aws_internet_gateway",
)

class AcdlTaggingStandard(BaseResourceCheck):
    def __init__(self):
        name = "Ensure all taggable AWS resources have required ACDL tags"
        check_id = "ACDL_TAG_NAMING"
        supported_resources = ["*"]  # all resources
        categories = [CheckCategories.GENERAL_SECURITY]
        super().__init__(name=name, check_id=check_id, categories=categories, supported_resources=supported_resources)

    def scan_resource_conf(self, conf, entity_type):
        # Skip non-taggable resources
        if entity_type in NON_TAGGABLE_TYPES:
            return CheckResult.PASSED
        # Check for a tags block
        tags = conf.get("tags")
        if not tags:
            return CheckResult.FAILED
        tag_keys = set()
        if isinstance(tags, list) and tags:
            tag_block = tags[0]
            if isinstance(tag_block, dict):
                tag_keys = set(tag_block.keys())
        elif isinstance(tags, dict):
            tag_keys = set(tags.keys())
        missing = [t for t in REQUIRED_TAGS if t not in tag_keys]
        if missing:
            return CheckResult.FAILED
        return CheckResult.PASSED

check = AcdlTaggingStandard()