"""
Resource tagging compliance detector.

This module contains detectors for:
- Untagged resources (EC2, EBS, RDS)
- Cost allocation tagging compliance
"""

from typing import Any, Dict, List

from stacksage.pricing import ebs_gb_month, estimate_ec2_monthly_cost


def _region_from_volume(vol: Dict[str, Any]) -> str:
    region = vol.get("Region")
    if region:
        return region
    az = vol.get("AvailabilityZone")
    if isinstance(az, str) and len(az) >= 2:
        return az[:-1]
    return None


def detect_untagged_resources(
    raw: Dict[str, Any], options: Dict[str, Any] = None
) -> List[Dict[str, Any]]:
    """
    Detect resources without ANY tags (indicates no governance).

    Changed from checking specific tag keys (too opinionated) to checking
    for complete absence of tags (indicates lack of basic resource management).

    This is less noisy and more universally applicable across organizations.

    Args:
        raw: Scanner output dictionary with resource lists
        options: Configuration options (check_tagging_compliance must be True to enable)
    """
    findings = []
    opts = options or {}

    # Only flag if customer enables this check (opt-in)
    if not opts.get("check_tagging_compliance", False):
        return findings

    # Check EC2 instances with ZERO tags
    for inst in raw.get("ec2", []):
        tags = inst.get("Tags", [])
        # Filter out AWS-managed tags
        user_tags = [t for t in tags if not t.get("Key", "").startswith("aws:")]

        if len(user_tags) == 0:
            estimated_cost = estimate_ec2_monthly_cost(
                inst.get("InstanceType"), region=None
            )
            findings.append(
                {
                    "type": "untagged_resource",
                    "resource_type": "ec2",
                    "id": inst.get("InstanceId"),
                    "region": inst.get("Region"),
                    "instance_type": inst.get("InstanceType"),
                    "estimated_monthly_cost_usd": estimated_cost,
                    "estimated_monthly_savings_usd": 0,
                    "potential_savings": 0,
                    "confidence": 1.0,
                    "severity": "low",
                    "recommended_action": "add-basic-tags",
                    "explanation": "EC2 instance has no user-defined tags. Add at minimum: Name, Environment, Owner tags for cost tracking and resource management.",
                    "remediation_commands": [
                        f"aws ec2 create-tags --resources {inst.get('InstanceId')} --tags Key=Name,Value=<descriptive-name> Key=Environment,Value=<prod|dev|test> Key=Owner,Value=<team>"
                    ],
                }
            )

    # Check EBS volumes with ZERO tags (and >50GB to focus on significant resources)
    for vol in raw.get("ebs", []):
        size = vol.get("Size", 0)
        if size < 50:  # Skip small volumes to reduce noise
            continue

        tags = vol.get("Tags", [])
        user_tags = [t for t in tags if not t.get("Key", "").startswith("aws:")]

        if len(user_tags) == 0:
            region = _region_from_volume(vol)
            estimated_cost = ebs_gb_month(size, vol.get("VolumeType", "gp3"), region)
            findings.append(
                {
                    "type": "untagged_resource",
                    "resource_type": "ebs",
                    "id": vol.get("VolumeId"),
                    "region": region,
                    "size_gb": size,
                    "estimated_monthly_cost_usd": estimated_cost,
                    "estimated_monthly_savings_usd": 0,
                    "potential_savings": 0,
                    "confidence": 1.0,
                    "severity": "low",
                    "recommended_action": "add-basic-tags",
                    "explanation": f"EBS volume ({size} GB) has no tags. Add tags to track ownership and prevent accidental deletion.",
                    "remediation_commands": [
                        f"aws ec2 create-tags --resources {vol.get('VolumeId')} --tags Key=Name,Value=<purpose> Key=Environment,Value=<prod|dev|test>"
                    ],
                }
            )

    # Check RDS instances with ZERO tags
    for db in raw.get("rds", []):
        tags = db.get("TagList", [])
        user_tags = [t for t in tags if not t.get("Key", "").startswith("aws:")]

        if (
            len(user_tags) == 0 and len(findings) < 20
        ):  # Limit findings to prevent report bloat
            findings.append(
                {
                    "type": "untagged_resource",
                    "resource_type": "rds",
                    "id": db.get("DBInstanceIdentifier"),
                    "region": db.get("Region"),
                    "engine": db.get("Engine"),
                    "estimated_monthly_cost_usd": 0,
                    "estimated_monthly_savings_usd": 0,
                    "potential_savings": 0,
                    "confidence": 1.0,
                    "severity": "low",
                    "recommended_action": "add-basic-tags",
                    "explanation": "RDS instance has no tags. Critical for cost allocation and backup policies.",
                    "remediation_commands": [
                        f"aws rds add-tags-to-resource --resource-name arn:aws:rds:region:account:db:{db.get('DBInstanceIdentifier')} --tags Key=Name,Value=<name> Key=Environment,Value=<prod|dev|test>"
                    ],
                }
            )

    return findings
