"""EBS Volume usage report."""

from dataclasses import dataclass
from datetime import datetime

import boto3
from rich.console import Console

console = Console()


@dataclass
class VolumeReport:
    """EBS Volume with its attachment status."""

    id: str
    name: str
    size_gb: int
    volume_type: str
    state: str
    created: datetime
    availability_zone: str
    iops: int | None
    throughput: int | None

    @property
    def is_orphaned(self) -> bool:
        return self.state == "available"

    def to_dict(self) -> dict:
        return {
            "id": self.id,
            "name": self.name,
            "size_gb": self.size_gb,
            "volume_type": self.volume_type,
            "state": self.state,
            "created": self.created.isoformat(),
            "availability_zone": self.availability_zone,
            "iops": self.iops,
            "throughput": self.throughput,
            "is_orphaned": self.is_orphaned,
        }


def get_volumes(session: boto3.Session) -> list[VolumeReport]:
    """Fetch all EBS volumes."""
    ec2 = session.client("ec2")
    paginator = ec2.get_paginator("describe_volumes")

    volumes = []
    for page in paginator.paginate():
        for vol in page["Volumes"]:
            tags = {t["Key"]: t["Value"] for t in vol.get("Tags", [])}
            name = tags.get("Name", "")

            volumes.append(
                VolumeReport(
                    id=vol["VolumeId"],
                    name=name,
                    size_gb=vol["Size"],
                    volume_type=vol["VolumeType"],
                    state=vol["State"],
                    created=vol["CreateTime"],
                    availability_zone=vol["AvailabilityZone"],
                    iops=vol.get("Iops"),
                    throughput=vol.get("Throughput"),
                )
            )

    console.print(f"Found {len(volumes)} EBS volumes")
    return volumes


def build_report(
    session: boto3.Session | None = None,
) -> list[VolumeReport]:
    """Build EBS Volume usage report."""
    if session is None:
        session = boto3.Session()

    return get_volumes(session)


def delete_volume(session: boto3.Session, volume_id: str) -> None:
    """Delete an EBS volume."""
    ec2 = session.client("ec2")
    ec2.delete_volume(VolumeId=volume_id)
    console.print(f"  Deleted volume {volume_id}")
