#!/usr/bin/env python3
"""CloudTrim Read-Only AWS Cloud Waste Auditor (v1.0.0)
=======================================================

SECURITY-FIRST GUARANTEE:
- 100% READ-ONLY: Only invokes AWS `sts:GetCallerIdentity`, `ce:Get*`,
  `ec2:Describe*`, `rds:Describe*`, and `cloudwatch:GetMetricStatistics`.
- ZERO WRITES / ZERO MUTATIONS: Never creates, modifies, stops, detaches,
  releases, or deletes any AWS resource.
- ZERO DATA EXFILTRATION: Runs strictly locally inside your own AWS CLI/SSO
  session and writes a redacted JSON waste summary to disk or stdout.
- Audit every single line below before running.

Minimal IAM Read-Only Policy JSON (`python3 cloudtrim_readonly_audit.py --dry-run-policy`):
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "CloudTrimReadOnlyAudit",
      "Effect": "Allow",
      "Action": [
        "sts:GetCallerIdentity",
        "ce:GetCostAndUsage",
        "ce:GetRightsizingRecommendation",
        "ec2:DescribeRegions",
        "ec2:DescribeVolumes",
        "ec2:DescribeAddresses",
        "ec2:DescribeSnapshots",
        "ec2:DescribeNatGateways",
        "ec2:DescribeInstances",
        "rds:DescribeDBInstances",
        "cloudwatch:GetMetricStatistics"
      ],
      "Resource": "*"
    }
  ]
}

Usage:
  pip install boto3
  python3 cloudtrim_readonly_audit.py --output cloudtrim_waste_report.json
  python3 cloudtrim_readonly_audit.py --regions us-east-1,us-west-2 --snapshot-age-days 90
  python3 cloudtrim_readonly_audit.py --dry-run-policy

Built by CloudTrim — NUTRINATURE LLC (Wyoming, USA) | https://outbound.truelinedesk.com/cloudtrim/
"""

from __future__ import annotations

import argparse
from datetime import datetime, timedelta, timezone
import json
import sys
from typing import Any

# Transparent AWS on-demand baseline heuristics (us-east-1 reference USD/month)
EBS_RATE_PER_GB_MONTH: dict[str, float] = {
    "gp2": 0.10,
    "gp3": 0.08,
    "io1": 0.125,
    "io2": 0.125,
    "st1": 0.045,
    "sc1": 0.015,
    "standard": 0.05,
}
GP2_TO_GP3_SAVINGS_PER_GB_MONTH = 0.02
SNAPSHOT_RATE_PER_GB_MONTH = 0.05
UNASSOCIATED_EIP_MONTHLY_USD = 3.60  # $0.005/hr * 720h
NAT_GATEWAY_HOURLY_MONTHLY_USD = 32.85  # $0.045/hr * 730h

# Rough EC2 instance family hourly baselines for heuristic low-CPU savings estimates
EC2_FAMILY_HOURLY_USD: dict[str, float] = {
    "t3.micro": 0.0104,
    "t3.small": 0.0208,
    "t3.medium": 0.0416,
    "t3.large": 0.0832,
    "t3.xlarge": 0.1664,
    "t3.2xlarge": 0.3328,
    "m5.large": 0.096,
    "m5.xlarge": 0.192,
    "m5.2xlarge": 0.384,
    "m6i.large": 0.096,
    "m6i.xlarge": 0.192,
    "m6i.2xlarge": 0.384,
    "c5.large": 0.085,
    "c5.xlarge": 0.17,
    "c5.2xlarge": 0.34,
    "c6i.large": 0.085,
    "c6i.xlarge": 0.17,
    "c6i.2xlarge": 0.34,
    "r5.large": 0.126,
    "r5.xlarge": 0.252,
    "r5.2xlarge": 0.504,
    "r6i.large": 0.126,
    "r6i.xlarge": 0.252,
}

RDS_CLASS_HOURLY_USD: dict[str, float] = {
    "db.t3.micro": 0.017,
    "db.t3.small": 0.034,
    "db.t3.medium": 0.068,
    "db.t3.large": 0.136,
    "db.t4g.medium": 0.065,
    "db.m5.large": 0.171,
    "db.m5.xlarge": 0.342,
    "db.m6g.large": 0.154,
    "db.m6g.xlarge": 0.308,
    "db.r5.large": 0.24,
    "db.r5.xlarge": 0.48,
    "db.r6g.large": 0.216,
    "db.r6g.xlarge": 0.432,
}

MINIMAL_READONLY_IAM_POLICY: dict[str, Any] = {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "CloudTrimReadOnlyAudit",
            "Effect": "Allow",
            "Action": [
                "sts:GetCallerIdentity",
                "ce:GetCostAndUsage",
                "ce:GetRightsizingRecommendation",
                "ec2:DescribeRegions",
                "ec2:DescribeVolumes",
                "ec2:DescribeAddresses",
                "ec2:DescribeSnapshots",
                "ec2:DescribeNatGateways",
                "ec2:DescribeInstances",
                "rds:DescribeDBInstances",
                "cloudwatch:GetMetricStatistics",
            ],
            "Resource": "*",
        }
    ],
}


def _estimate_ec2_monthly_usd(instance_type: str) -> float:
    hourly = EC2_FAMILY_HOURLY_USD.get(instance_type)
    if hourly is None:
        if ".4xlarge" in instance_type:
            hourly = 0.72
        elif ".2xlarge" in instance_type:
            hourly = 0.36
        elif ".xlarge" in instance_type:
            hourly = 0.18
        elif ".large" in instance_type:
            hourly = 0.09
        else:
            hourly = 0.045
    return round(hourly * 730.0, 2)


def _estimate_rds_monthly_usd(db_class: str, multi_az: bool) -> float:
    hourly = RDS_CLASS_HOURLY_USD.get(db_class)
    if hourly is None:
        if ".2xlarge" in db_class:
            hourly = 0.68
        elif ".xlarge" in db_class:
            hourly = 0.34
        elif ".large" in db_class:
            hourly = 0.17
        else:
            hourly = 0.07
    mult = 2.0 if multi_az else 1.0
    return round(hourly * 730.0 * mult, 2)


def _tag_name(tags: list[dict[str, str]] | None) -> str:
    for tag in tags or []:
        if tag.get("Key") == "Name":
            return str(tag.get("Value") or "")
    return ""


def _cw_metric_stat(
    cw_client: Any,
    *,
    namespace: str,
    metric_name: str,
    dimensions: list[dict[str, str]],
    stat: str,
    days: int = 14,
) -> float | None:
    end = datetime.now(timezone.utc)
    start = end - timedelta(days=days)
    try:
        resp = cw_client.get_metric_statistics(
            Namespace=namespace,
            MetricName=metric_name,
            Dimensions=dimensions,
            StartTime=start,
            EndTime=end,
            Period=86400,
            Statistics=[stat],
        )
        points = resp.get("Datapoints") or []
        if not points:
            return None
        vals = [float(p.get(stat, 0.0)) for p in points if stat in p]
        if not vals:
            return None
        if stat == "Sum":
            return round(sum(vals), 2)
        if stat == "Maximum":
            return round(max(vals), 2)
        return round(sum(vals) / len(vals), 2)
    except Exception:
        return None


def _audit_cost_explorer(session: Any) -> dict[str, Any]:
    """Read-only 30-day AWS Cost Explorer summary + native rightsizing recommendations."""
    result: dict[str, Any] = {
        "available": False,
        "last_30d_unblended_usd": None,
        "top_services_30d": [],
        "aws_rightsizing_monthly_savings_usd": 0.0,
        "aws_rightsizing_count": 0,
    }
    try:
        ce = session.client("ce", region_name="us-east-1")
        end_dt = datetime.now(timezone.utc).date()
        start_dt = end_dt - timedelta(days=30)
        cost_resp = ce.get_cost_and_usage(
            TimePeriod={"Start": start_dt.isoformat(), "End": end_dt.isoformat()},
            Granularity="MONTHLY",
            Metrics=["UnblendedCost"],
            GroupBy=[{"Type": "DIMENSION", "Key": "SERVICE"}],
        )
        svc_totals: dict[str, float] = {}
        for period in cost_resp.get("ResultsByTime") or []:
            for grp in period.get("Groups") or []:
                svc = (grp.get("Keys") or ["Other"])[0]
                amt = float(((grp.get("Metrics") or {}).get("UnblendedCost") or {}).get("Amount") or 0.0)
                svc_totals[svc] = svc_totals.get(svc, 0.0) + amt
        top = sorted(svc_totals.items(), key=lambda kv: kv[1], reverse=True)[:10]
        result["available"] = True
        result["last_30d_unblended_usd"] = round(sum(svc_totals.values()), 2)
        result["top_services_30d"] = [{"service": s, "usd_30d": round(v, 2)} for s, v in top if v > 0.01]

        try:
            rs_resp = ce.get_rightsizing_recommendation(Service="AmazonEC2")
            summary = rs_resp.get("Summary") or {}
            result["aws_rightsizing_monthly_savings_usd"] = round(
                float(summary.get("EstimatedTotalMonthlySavingsAmount") or 0.0), 2
            )
            result["aws_rightsizing_count"] = int(summary.get("TotalRecommendationCount") or 0)
        except Exception:
            pass
    except Exception as exc:
        result["note"] = f"Cost Explorer skipped ({type(exc).__name__})"
    return result


def _audit_region(
    session: Any,
    region: str,
    *,
    snapshot_age_days: int,
    low_cpu_threshold: float,
) -> dict[str, Any]:
    ec2 = session.client("ec2", region_name=region)
    rds = session.client("rds", region_name=region)
    cw = session.client("cloudwatch", region_name=region)
    now = datetime.now(timezone.utc)
    snap_cutoff = now - timedelta(days=snapshot_age_days)

    unattached_ebs: list[dict[str, Any]] = []
    gp2_upgrade_candidates: list[dict[str, Any]] = []
    idle_eips: list[dict[str, Any]] = []
    old_snapshots: list[dict[str, Any]] = []
    idle_nat_gateways: list[dict[str, Any]] = []
    ec2_waste_candidates: list[dict[str, Any]] = []
    rds_waste_candidates: list[dict[str, Any]] = []

    # 1. EBS Volumes (unattached + gp2->gp3 upgrade savings)
    paginator = ec2.get_paginator("describe_volumes")
    for page in paginator.paginate():
        for vol in page.get("Volumes") or []:
            vol_id = str(vol.get("VolumeId") or "")
            size_gb = int(vol.get("Size") or 0)
            vtype = str(vol.get("VolumeType") or "gp2")
            state = str(vol.get("State") or "")
            name = _tag_name(vol.get("Tags"))
            rate = EBS_RATE_PER_GB_MONTH.get(vtype, 0.10)
            if state == "available":
                unattached_ebs.append(
                    {
                        "region": region,
                        "volume_id": vol_id,
                        "name": name,
                        "volume_type": vtype,
                        "size_gb": size_gb,
                        "est_monthly_usd": round(size_gb * rate, 2),
                    }
                )
            elif vtype == "gp2" and size_gb >= 20:
                gp2_upgrade_candidates.append(
                    {
                        "region": region,
                        "volume_id": vol_id,
                        "name": name,
                        "size_gb": size_gb,
                        "est_monthly_savings_usd": round(size_gb * GP2_TO_GP3_SAVINGS_PER_GB_MONTH, 2),
                    }
                )

    # 2. Unassociated Elastic IPs
    for addr in (ec2.describe_addresses().get("Addresses") or []):
        if not addr.get("AssociationId"):
            idle_eips.append(
                {
                    "region": region,
                    "allocation_id": str(addr.get("AllocationId") or ""),
                    "public_ip": str(addr.get("PublicIp") or ""),
                    "est_monthly_usd": UNASSOCIATED_EIP_MONTHLY_USD,
                }
            )

    # 3. Old EBS Snapshots (> snapshot_age_days)
    snap_paginator = ec2.get_paginator("describe_snapshots")
    for page in snap_paginator.paginate(OwnerIds=["self"]):
        for snap in page.get("Snapshots") or []:
            start_time = snap.get("StartTime")
            if start_time and start_time < snap_cutoff:
                size_gb = int(snap.get("VolumeSize") or 0)
                age_days = (now - start_time).days
                old_snapshots.append(
                    {
                        "region": region,
                        "snapshot_id": str(snap.get("SnapshotId") or ""),
                        "age_days": age_days,
                        "volume_size_gb": size_gb,
                        "est_monthly_usd": round(size_gb * SNAPSHOT_RATE_PER_GB_MONTH, 2),
                    }
                )

    # 4. Idle / Low-Traffic NAT Gateways (14-day CloudWatch BytesOutToDestination)
    for nat in (ec2.describe_nat_gateways().get("NatGateways") or []):
        if nat.get("State") != "available":
            continue
        nat_id = str(nat.get("NatGatewayId") or "")
        bytes_out = _cw_metric_stat(
            cw,
            namespace="AWS/NATGateway",
            metric_name="BytesOutToDestination",
            dimensions=[{"Name": "NatGatewayId", "Value": nat_id}],
            stat="Sum",
            days=14,
        )
        if bytes_out is None or bytes_out < 100_000_000:  # < 100 MB in 14 days
            idle_nat_gateways.append(
                {
                    "region": region,
                    "nat_gateway_id": nat_id,
                    "vpc_id": str(nat.get("VpcId") or ""),
                    "bytes_out_14d": bytes_out or 0.0,
                    "est_monthly_usd": NAT_GATEWAY_HOURLY_MONTHLY_USD,
                }
            )

    # 5. Low-Utilization Running EC2 Instances (< low_cpu_threshold% avg 14d CPU)
    inst_paginator = ec2.get_paginator("describe_instances")
    for page in inst_paginator.paginate(Filters=[{"Name": "instance-state-name", "Values": ["running"]}]):
        for res in page.get("Reservations") or []:
            for inst in res.get("Instances") or []:
                inst_id = str(inst.get("InstanceId") or "")
                itype = str(inst.get("InstanceType") or "")
                name = _tag_name(inst.get("Tags"))
                avg_cpu = _cw_metric_stat(
                    cw,
                    namespace="AWS/EC2",
                    metric_name="CPUUtilization",
                    dimensions=[{"Name": "InstanceId", "Value": inst_id}],
                    stat="Average",
                    days=14,
                )
                if avg_cpu is not None and avg_cpu < low_cpu_threshold:
                    monthly_est = _estimate_ec2_monthly_usd(itype)
                    # Conservative 50% savings assumption (downsize one size class or off-hours schedule)
                    ec2_waste_candidates.append(
                        {
                            "region": region,
                            "instance_id": inst_id,
                            "name": name,
                            "instance_type": itype,
                            "avg_cpu_14d_pct": avg_cpu,
                            "est_monthly_savings_usd": round(monthly_est * 0.50, 2),
                        }
                    )

    # 6. Idle or Non-Prod Multi-AZ RDS Instances
    try:
        rds_paginator = rds.get_paginator("describe_db_instances")
        for page in rds_paginator.paginate():
            for db in page.get("DBInstances") or []:
                db_id = str(db.get("DBInstanceIdentifier") or "")
                db_class = str(db.get("DBInstanceClass") or "")
                multi_az = bool(db.get("MultiAZ"))
                max_conns = _cw_metric_stat(
                    cw,
                    namespace="AWS/RDS",
                    metric_name="DatabaseConnections",
                    dimensions=[{"Name": "DBInstanceIdentifier", "Value": db_id}],
                    stat="Maximum",
                    days=14,
                )
                is_nonprod = any(tok in db_id.lower() for tok in ("dev", "stag", "stg", "qa", "test", "sandbox"))
                monthly_est = _estimate_rds_monthly_usd(db_class, multi_az)
                if max_conns is not None and max_conns == 0:
                    rds_waste_candidates.append(
                        {
                            "region": region,
                            "db_instance_id": db_id,
                            "db_class": db_class,
                            "multi_az": multi_az,
                            "reason": "zero_connections_14d",
                            "est_monthly_savings_usd": round(monthly_est * 0.85, 2),
                        }
                    )
                elif is_nonprod and multi_az:
                    rds_waste_candidates.append(
                        {
                            "region": region,
                            "db_instance_id": db_id,
                            "db_class": db_class,
                            "multi_az": multi_az,
                            "reason": "nonprod_multi_az_enabled",
                            "est_monthly_savings_usd": round(monthly_est * 0.50, 2),
                        }
                    )
    except Exception:
        pass

    return {
        "unattached_ebs": unattached_ebs,
        "gp2_upgrade_candidates": gp2_upgrade_candidates,
        "idle_eips": idle_eips,
        "old_snapshots": old_snapshots,
        "idle_nat_gateways": idle_nat_gateways,
        "ec2_waste_candidates": ec2_waste_candidates,
        "rds_waste_candidates": rds_waste_candidates,
    }


def run_audit(
    *,
    regions: list[str] | None = None,
    profile: str | None = None,
    snapshot_age_days: int = 90,
    low_cpu_threshold: float = 5.0,
    include_account_id: bool = False,
) -> dict[str, Any]:
    """Execute full read-only AWS FinOps audit and return structured JSON report."""
    try:
        import boto3  # type: ignore
    except ImportError as exc:
        raise RuntimeError("boto3 is required to query AWS APIs. Install with: pip install boto3") from exc

    session = boto3.Session(profile_name=profile) if profile else boto3.Session()
    sts = session.client("sts")
    ident = sts.get_caller_identity()
    raw_acct = str(ident.get("Account") or "unknown")
    acct_label = raw_acct if include_account_id else (f"****{raw_acct[-4:]}" if len(raw_acct) >= 4 else "****")

    if not regions:
        ec2_default = session.client("ec2", region_name=session.region_name or "us-east-1")
        regions = [
            str(r["RegionName"])
            for r in (ec2_default.describe_regions(AllRegions=False).get("Regions") or [])
            if r.get("RegionName")
        ]

    cost_explorer = _audit_cost_explorer(session)

    combined: dict[str, list[dict[str, Any]]] = {
        "unattached_ebs": [],
        "gp2_upgrade_candidates": [],
        "idle_eips": [],
        "old_snapshots": [],
        "idle_nat_gateways": [],
        "ec2_waste_candidates": [],
        "rds_waste_candidates": [],
    }
    region_errors: dict[str, str] = {}
    for reg in regions:
        try:
            reg_out = _audit_region(
                session,
                reg,
                snapshot_age_days=snapshot_age_days,
                low_cpu_threshold=low_cpu_threshold,
            )
            for k in combined:
                combined[k].extend(reg_out[k])
        except Exception as exc:
            region_errors[reg] = type(exc).__name__

    savings_by_category = {
        "unattached_ebs_monthly_usd": round(sum(x["est_monthly_usd"] for x in combined["unattached_ebs"]), 2),
        "gp2_to_gp3_monthly_usd": round(sum(x["est_monthly_savings_usd"] for x in combined["gp2_upgrade_candidates"]), 2),
        "idle_eips_monthly_usd": round(sum(x["est_monthly_usd"] for x in combined["idle_eips"]), 2),
        "old_snapshots_monthly_usd": round(sum(x["est_monthly_usd"] for x in combined["old_snapshots"]), 2),
        "idle_nat_gateways_monthly_usd": round(sum(x["est_monthly_usd"] for x in combined["idle_nat_gateways"]), 2),
        "low_cpu_ec2_monthly_usd": round(sum(x["est_monthly_savings_usd"] for x in combined["ec2_waste_candidates"]), 2),
        "idle_or_nonprod_rds_monthly_usd": round(sum(x["est_monthly_savings_usd"] for x in combined["rds_waste_candidates"]), 2),
    }
    total_monthly = round(sum(savings_by_category.values()), 2)

    return {
        "tool": "cloudtrim_readonly_audit",
        "version": "1.0.0",
        "mode": "READ_ONLY",
        "generated_at_utc": datetime.now(timezone.utc).isoformat(),
        "aws_account": acct_label,
        "regions_scanned": regions,
        "region_errors": region_errors,
        "cost_explorer_30d": cost_explorer,
        "summary": {
            "unattached_ebs_count": len(combined["unattached_ebs"]),
            "gp2_upgrade_count": len(combined["gp2_upgrade_candidates"]),
            "idle_eip_count": len(combined["idle_eips"]),
            "old_snapshot_count": len(combined["old_snapshots"]),
            "idle_nat_gateway_count": len(combined["idle_nat_gateways"]),
            "low_cpu_ec2_count": len(combined["ec2_waste_candidates"]),
            "rds_waste_count": len(combined["rds_waste_candidates"]),
            "savings_by_category_usd": savings_by_category,
            "estimated_monthly_savings_usd": total_monthly,
            "estimated_annual_savings_usd": round(total_monthly * 12.0, 2),
        },
        "findings": combined,
        "next_step": (
            "Send this redacted JSON summary to hola@truelinedesk.com for a 48h CloudTrim Deep Teardown ($299) "
            "or 72h Terraform/CLI Waste Elimination Sprint ($999) — https://outbound.truelinedesk.com/cloudtrim/"
        ),
    }


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        description="CloudTrim Read-Only AWS Cloud Waste Auditor (zero mutations, local JSON output)."
    )
    parser.add_argument("--regions", default="", help="Comma-separated AWS regions (default: all enabled regions).")
    parser.add_argument("--profile", default=None, help="Optional AWS CLI/SSO profile name.")
    parser.add_argument("--snapshot-age-days", type=int, default=90, help="Flag owned snapshots older than N days (default: 90).")
    parser.add_argument("--low-cpu-threshold", type=float, default=5.0, help="Flag running EC2 with 14d avg CPU below % (default: 5.0).")
    parser.add_argument("--include-account-id", action="store_true", help="Include full AWS account ID instead of last-4 redaction.")
    parser.add_argument("--output", default="", help="Write JSON summary to file path instead of stdout.")
    parser.add_argument("--dry-run-policy", action="store_true", help="Print minimal read-only IAM policy JSON and exit.")
    args = parser.parse_args(argv)

    if args.dry_run_policy:
        print(json.dumps(MINIMAL_READONLY_IAM_POLICY, indent=2))
        return 0

    region_list = [r.strip() for r in args.regions.split(",") if r.strip()] or None
    report = run_audit(
        regions=region_list,
        profile=args.profile,
        snapshot_age_days=max(7, args.snapshot_age_days),
        low_cpu_threshold=max(0.5, args.low_cpu_threshold),
        include_account_id=args.include_account_id,
    )
    payload = json.dumps(report, indent=2)
    if args.output:
        with open(args.output, "w", encoding="utf-8") as fh:
            fh.write(payload + "\n")
        print(
            f"[CloudTrim] Read-only scan complete -> {args.output} "
            f"(est. ${report['summary']['estimated_monthly_savings_usd']:,.2f}/mo recoverable)"
        )
    else:
        print(payload)
    return 0


if __name__ == "__main__":
    sys.exit(main())
