import boto3
import json
from datetime import datetime, timedelta


def get_aws_waste_data():
    print("Scanning AWS environment for cost optimization opportunities...")
    audit_data = {}

    # 1. Check for Unattached Elastic IPs
    try:
        ec2 = boto3.client('ec2')
        eips = ec2.describe_addresses()
        unattached_eip_count = sum(
            1 for eip in eips.get('Addresses', []) if 'InstanceId' not in eip
        )
        audit_data['unattached_elastic_ips'] = {
            "count": unattached_eip_count,
            "estimated_monthly_waste_usd": round(unattached_eip_count * 3.60, 2)
        }
        print(f"Found {unattached_eip_count} unattached Elastic IPs.")
    except Exception:
        audit_data['unattached_elastic_ips'] = "Skipped: Missing EC2 read permissions."

    # 2. Check for Unattached/Available EBS Volumes
    try:
        volumes = ec2.describe_volumes(Filters=[{'Name': 'status', 'Values': ['available']}])
        unattached_ebs_count = len(volumes.get('Volumes', []))
        ebs_gb = sum(v.get('Size', 0) for v in volumes.get('Volumes', []))
        audit_data['unattached_ebs_volumes'] = {
            "count": unattached_ebs_count,
            "total_gb": ebs_gb,
            "estimated_monthly_waste_usd": round(ebs_gb * 0.08, 2)
        }
        print(f"Found {unattached_ebs_count} unattached EBS volumes ({ebs_gb} GB).")
    except Exception:
        audit_data['unattached_ebs_volumes'] = "Skipped: Missing EC2 Volume permissions."

    # 3. Get Last 30 Days Spend via Cost Explorer
    try:
        ce = boto3.client('ce')
        start_date = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')
        end_date = datetime.now().strftime('%Y-%m-%d')

        spend = ce.get_cost_and_usage(
            TimePeriod={'Start': start_date, 'End': end_date},
            Granularity='MONTHLY',
            Metrics=['UnblendedCost']
        )
        total_spend = spend['ResultsByTime'][0]['Total']['UnblendedCost']['Amount']
        audit_data['last_30_days_spend_usd'] = round(float(total_spend), 2)
        print(f"Retrieved 30-day spend data.")
    except Exception:
        audit_data['last_30_days_spend_usd'] = "Skipped: Missing Cost Explorer permissions."

    # Save to a local JSON file
    filename = "cloudorbit-audit.json"
    with open(filename, "w") as f:
        json.dump(audit_data, f, indent=4)

    print(f"\nSuccess! Audit data saved locally to {filename}")
    print("This file contains no sensitive credentials and is ready for analysis.")


if __name__ == "__main__":
    get_aws_waste_data()
