"""
Cost Summary Widget - Display cost and token usage summary.

Provides:
- Daily/monthly cost tracking
- Token usage display
- Budget progress indicator
- Alert indicators
"""

from typing import Optional

from textual.app import ComposeResult
from textual.containers import Horizontal
from textual.widgets import Static, ProgressBar
from textual.reactive import reactive


class CostSummaryBar(Static):
    """Bottom bar displaying cost summary and alerts."""

    DEFAULT_CSS = """
    CostSummaryBar {
        height: 3;
        background: $surface;
        layout: horizontal;
        padding: 0 2;
        content-align: center middle;
    }

    .cost-section {
        width: auto;
        margin: 0 2;
    }

    .cost-label {
        color: $text-muted;
    }

    .cost-value {
        color: $text;
        text-style: bold;
    }

    .cost-warning {
        color: $warning;
    }

    .cost-critical {
        color: $error;
    }

    .budget-bar {
        width: 20;
        margin: 0 2;
    }

    .alert-badge {
        background: $warning;
        color: $text;
        padding: 0 1;
        margin: 0 1;
    }

    .alert-critical {
        background: $error;
    }

    .divider {
        color: $text-muted;
        margin: 0 1;
    }
    """

    today_usd: reactive[float] = reactive(0.0)
    month_usd: reactive[float] = reactive(0.0)
    tokens_today: reactive[int] = reactive(0)
    budget_percent: reactive[float] = reactive(0.0)
    alert_count: reactive[int] = reactive(0)

    def compose(self) -> ComposeResult:
        """Compose the cost bar layout."""
        with Horizontal():
            yield Static("COST TODAY:", classes="cost-section cost-label")
            yield Static(id="cost-today", classes="cost-section cost-value")

            yield Static("|", classes="divider")

            yield Static("MONTH:", classes="cost-section cost-label")
            yield Static(id="cost-month", classes="cost-section cost-value")

            yield Static("|", classes="divider")

            yield Static("TOKENS:", classes="cost-section cost-label")
            yield Static(id="tokens-today", classes="cost-section cost-value")

            yield Static("|", classes="divider")

            yield Static("BUDGET:", classes="cost-section cost-label")
            yield ProgressBar(id="budget-bar", total=100, show_eta=False, classes="budget-bar")

            yield Static(id="alert-badge", classes="cost-section")

    def on_mount(self) -> None:
        """Initialize display on mount."""
        self._update_display()

    def update_costs(self, costs: dict) -> None:
        """Update cost display from data dictionary."""
        self.today_usd = costs.get("today_usd", 0.0)
        self.month_usd = costs.get("month_usd", 0.0)
        self.tokens_today = costs.get("tokens_today", 0)
        self.budget_percent = costs.get("budget_percent", 0.0)
        self.alert_count = costs.get("alerts", 0)
        self._update_display()

    def _update_display(self) -> None:
        """Update all display elements."""
        try:
            # Today's cost
            today_str = f"${self.today_usd:.2f}"
            today_class = ""
            if self.budget_percent >= 90:
                today_str = f"[red]{today_str}[/red]"
            elif self.budget_percent >= 75:
                today_str = f"[yellow]{today_str}[/yellow]"
            self.query_one("#cost-today", Static).update(today_str)

            # Month cost
            month_str = f"${self.month_usd:.2f}"
            self.query_one("#cost-month", Static).update(month_str)

            # Tokens
            tokens_str = f"{self.tokens_today:,}"
            self.query_one("#tokens-today", Static).update(tokens_str)

            # Budget bar
            self.query_one("#budget-bar", ProgressBar).progress = min(100, self.budget_percent)

            # Alert badge
            if self.alert_count > 0:
                alert_str = f"⚠ {self.alert_count} alerts"
                if self.budget_percent >= 90:
                    alert_str = f"[bold red]{alert_str}[/bold red]"
                else:
                    alert_str = f"[bold yellow]{alert_str}[/bold yellow]"
                self.query_one("#alert-badge", Static).update(alert_str)
            else:
                self.query_one("#alert-badge", Static).update("")

        except Exception:
            pass  # Widget not fully mounted

    def watch_today_usd(self, value: float) -> None:
        """React to cost changes."""
        self._update_display()

    def watch_alert_count(self, value: int) -> None:
        """React to alert count changes."""
        self._update_display()
