from datetime import datetime

import typer
from flashenv.core.state import list_envs
from rich.console import Console
from rich.table import Table
from flashenv.utils.init import check_init

console = Console()

# Constants: prices per hour for t2.micro (region: eu-west-1)
HOURLY_RATE = 0.0126
SPOT_HOURLY_RATE = 0.0038


def cost_command():
    """
    Displays a breakdown of costs based on uptime.
    """

    check_init()

    envs = list_envs()
    if not envs:
        console.print("📭 No environments found. Cost is $0.00.", style="bold green")
        raise typer.Exit()

    table = Table(
        title="💰 Estimated FlashEnv Costs (t2.micro)",
        show_footer=True,
        caption=f"*Based on On-Demand rate (${str(HOURLY_RATE)}/hr). Does not include EBS storage or Data Transfer.",
    )

    table.add_column("Environment", style="cyan")
    table.add_column("Uptime", style="dim")
    table.add_column("Hourly Rate", justify="right")
    table.add_column("Est. Cost", justify="right", style="bold green", footer_style="bold green")

    total_cost = 0.0

    for name, data in envs.items():
        created_at_str = data.get("created_at")
        if not created_at_str:
            continue

        try:
            start_time = datetime.fromisoformat(created_at_str)
            current_time = datetime.now()
            duration = current_time - start_time
            hours_run = duration.total_seconds() / 3600

            is_spot = data.get("is_spot", False)
            rate = SPOT_HOURLY_RATE if is_spot else HOURLY_RATE
            cost = hours_run * rate
            total_cost += cost
            duration_str = str(duration).split(".")[0]
            table.add_row(name, duration_str, f"${rate}", f"${cost:.4f}")
        except ValueError:
            continue
    table.columns[3].footer = f"${total_cost:.4f}"
    console.print(table)
