"""Rich console output formatting."""

from rich.console import Console
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.table import Table
from rich.text import Text

from ..core.scorer import FOMOScore, FOMOVerdict
from ..signals.base import RiskLevel, SignalResult


class DisplayFormatter:
    """Format FOMO analysis results for console display."""

    def __init__(self):
        """Initialize formatter."""
        self.console = Console()

    def get_verdict_style(self, verdict: FOMOVerdict) -> str:
        """Get Rich style for verdict."""
        styles = {
            FOMOVerdict.GREEN: "bold green",
            FOMOVerdict.YELLOW: "bold yellow",
            FOMOVerdict.ORANGE: "bold orange1",
            FOMOVerdict.RED: "bold red",
        }
        return styles.get(verdict, "white")

    def get_risk_emoji(self, verdict: FOMOVerdict) -> str:
        """Get emoji for risk level."""
        emojis = {
            FOMOVerdict.GREEN: "[green]OK[/green]",
            FOMOVerdict.YELLOW: "[yellow]!![/yellow]",
            FOMOVerdict.ORANGE: "[orange1]!!![/orange1]",
            FOMOVerdict.RED: "[red]XXXX[/red]",
        }
        return emojis.get(verdict, "")

    def display_score(self, fomo_score: FOMOScore, detailed: bool = False) -> None:
        """Display FOMO score analysis."""
        style = self.get_verdict_style(fomo_score.verdict)
        risk_indicator = self.get_risk_emoji(fomo_score.verdict)

        # Header with score
        score_text = Text()
        score_text.append(f"\nFOMO Score for ", style="bold")
        score_text.append(f"{fomo_score.symbol}", style="bold cyan")
        score_text.append(f": ", style="bold")
        score_text.append(f"{fomo_score.score:.0f}/100", style=style)
        score_text.append(f" {risk_indicator}")

        self.console.print(score_text)

        # Verdict panel
        verdict_text = self._get_verdict_description(fomo_score.verdict)
        panel = Panel(
            verdict_text,
            title=f"[{style}]{fomo_score.verdict.value.upper()}[/{style}]",
            border_style=fomo_score.color,
        )
        self.console.print(panel)

        # Signal breakdown table
        if fomo_score.signal_results:
            self._display_signal_table(fomo_score.signal_results)

        # Detailed indicator breakdown
        if detailed:
            self._display_detailed_indicators(fomo_score.signal_results)

        # Recommendation
        self.console.print(f"\n[bold]Recommendation:[/bold]")
        self.console.print(f"  {fomo_score.recommendation}\n")

        # Cooldown suggestion
        if fomo_score.suggested_cooldown_hours > 0:
            self.console.print(
                f"[dim]Suggested wait time: {fomo_score.suggested_cooldown_hours} hours[/dim]\n"
            )

    def _get_verdict_description(self, verdict: FOMOVerdict) -> str:
        """Get description for verdict."""
        descriptions = {
            FOMOVerdict.GREEN: "Low FOMO risk - conditions appear reasonable for entry",
            FOMOVerdict.YELLOW: "Moderate risk - proceed with caution, consider DCA",
            FOMOVerdict.ORANGE: "High risk - strong FOMO signals detected, consider waiting",
            FOMOVerdict.RED: "EXTREME RISK - you are likely buying the top!",
        }
        return descriptions.get(verdict, "Unknown")

    def _display_signal_table(self, signals: list[SignalResult]) -> None:
        """Display signal breakdown table."""
        table = Table(title="Signal Analysis", show_header=True)
        table.add_column("Signal", style="cyan")
        table.add_column("Score", justify="center")
        table.add_column("Weight", justify="center")
        table.add_column("Risk", justify="center")
        table.add_column("Status")

        for signal in signals:
            if not signal.available:
                table.add_row(
                    signal.category.value.title(),
                    "-",
                    f"{signal.weight:.0%}",
                    "-",
                    "[dim]No data[/dim]",
                )
                continue

            score_style = self._get_score_style(signal.score)
            risk_style = self._get_risk_style(signal.risk_level)

            table.add_row(
                signal.category.value.title(),
                f"[{score_style}]{signal.score:.0f}[/{score_style}]",
                f"{signal.weight:.0%}",
                f"[{risk_style}]{signal.risk_level.value}[/{risk_style}]",
                signal.summary[:40] + "..." if len(signal.summary) > 40 else signal.summary,
            )

        self.console.print(table)

    def _display_detailed_indicators(self, signals: list[SignalResult]) -> None:
        """Display detailed indicator breakdown."""
        for signal in signals:
            if not signal.available or not signal.indicators:
                continue

            self.console.print(f"\n[bold]{signal.category.value.title()} Indicators:[/bold]")

            for indicator in signal.indicators:
                score_style = self._get_score_style(indicator.score)
                self.console.print(
                    f"  [{score_style}]{indicator.score:.0f}[/{score_style}] "
                    f"[cyan]{indicator.name}[/cyan]: {indicator.description}"
                )

    def _get_score_style(self, score: float) -> str:
        """Get style based on score."""
        if score <= 30:
            return "green"
        elif score <= 60:
            return "yellow"
        elif score <= 80:
            return "orange1"
        else:
            return "red"

    def _get_risk_style(self, risk: RiskLevel) -> str:
        """Get style based on risk level."""
        styles = {
            RiskLevel.LOW: "green",
            RiskLevel.MODERATE: "yellow",
            RiskLevel.HIGH: "orange1",
            RiskLevel.EXTREME: "red",
        }
        return styles.get(risk, "white")

    def display_config_list(self, keys: dict[str, str | None]) -> None:
        """Display configured API keys."""
        table = Table(title="API Keys Configuration")
        table.add_column("Provider", style="cyan")
        table.add_column("Status")
        table.add_column("Key (masked)")

        for provider, key in keys.items():
            if key:
                table.add_row(provider, "[green]Configured[/green]", key)
            else:
                table.add_row(provider, "[dim]Not set[/dim]", "-")

        self.console.print(table)

    def display_cooldown_status(self, cooldowns: list[dict]) -> None:
        """Display active cooldowns."""
        if not cooldowns:
            self.console.print("[dim]No active cooldowns[/dim]")
            return

        table = Table(title="Active Cooldowns")
        table.add_column("Symbol", style="cyan")
        table.add_column("Started")
        table.add_column("Expires")
        table.add_column("Remaining")

        for cd in cooldowns:
            table.add_row(
                cd["symbol"],
                cd["started"],
                cd["expires"],
                cd["remaining"],
            )

        self.console.print(table)

    def display_error(self, message: str) -> None:
        """Display error message."""
        self.console.print(f"[red]Error:[/red] {message}")

    def display_success(self, message: str) -> None:
        """Display success message."""
        self.console.print(f"[green]Success:[/green] {message}")

    def create_progress(self) -> Progress:
        """Create a progress spinner."""
        return Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
            console=self.console,
        )
