"""Logos ADK TUI IDE - Perfect Cline-style interface."""
from __future__ import annotations

import asyncio
import time
import random
from datetime import datetime

from textual.app import App, ComposeResult
from textual.containers import Container, Horizontal, Vertical, ScrollableContainer
from textual.widgets import Input, Static, Label
from textual.binding import Binding
from rich.text import Text
from rich.markdown import Markdown as RichMarkdown
from rich.panel import Panel

from logos_adk.runnable_config_loader import load_runnable_from_config

class AnimatedLogos(Static):
    """Анимированная надпись Logos."""
    def on_mount(self) -> None:
        self.animation_colors = [
            "#ff7b72", "#d19a66", "#e5c07b", "#98c379", 
            "#56b6c2", "#61afef", "#c678dd"
        ]
        self.color_index = 0
        self.logos_art = r"""
  _       ____    ____   ____    _____ 
 | |     / __ \  / ___| / __ \  / ____|
 | |    | |  | || |  _ | |  | || (___  
 | |    | |  | || | |_|| |  | | \___ \ 
 | |____| |__| || |__| | |__| | ____) |
 |______|\____/  \____| \____/ |_____/ 
"""
        self.update(self.logos_art)
        self.set_interval(0.15, self.animate_colors)

    def animate_colors(self) -> None:
        self.color_index = (self.color_index + 1) % len(self.animation_colors)
        self.styles.color = self.animation_colors[self.color_index]

class WelcomeWidget(Container):
    def compose(self) -> ComposeResult:
        yield AnimatedLogos(id="logos-art")
        yield Label("What can I do for you?", id="welcome-text")

class ActionWidget(Static):
    """Widget for showing tool actions like in Cline."""
    def __init__(self, title: str, content: str, icon: str = "✓", color: str = "#98c379"):
        super().__init__()
        self.action_title = title
        self.content = content
        self.icon = icon
        self.color = color

    def render(self) -> Panel:
        return Panel(
            RichMarkdown(f"```python\n{self.content}\n```"),
            title=f"[{self.color} bold]{self.icon} {self.action_title}[/]",
            border_style=self.color,
            padding=(0, 1),
            style="on transparent"
        )

class MessageWidget(Static):
    """Clean messages with icons."""
    def __init__(self, role: str, content: str):
        super().__init__()
        self.role = role
        self.content = content

    def render(self) -> Text:
        is_agent = self.role == "Agent"
        icon = "✦ " if is_agent else "● "
        color = "#c678dd" if is_agent else "#98c379"
        
        res = Text()
        res.append(f"\n{icon}", style=f"bold {color}")
        res.append(f"{self.content}\n", style="#cccccc")
        return res

class StatusInfoLine(Static):
    """Анимированная строка состояния над вводом."""
    
    PHRASES = [
        "Following the white rabbit",
        "Connecting to the matrix",
        "Synthesizing tools",
        "Analyzing context",
        "Thinking deeply",
        "Loading logic modules"
    ]
    
    def __init__(self, **kwargs):
        super().__init__("", **kwargs)
        self.is_busy = False
        self.start_time = 0
        self.tokens = 0
        self.dots = 0
        self.phrase = ""
        self._timer = None

    def on_mount(self) -> None:
        self.update("")

    def start_action(self):
        self.is_busy = True
        self.start_time = time.time()
        self.tokens = 0
        self.phrase = random.choice(self.PHRASES)
        self.dots = 0
        self.update_content()
        if self._timer:
            self._timer.stop()
        self._timer = self.set_interval(0.5, self.update_content)

    def stop_action(self):
        self.is_busy = False
        if self._timer:
            self._timer.stop()
            self._timer = None
        self.update("")

    def update_tokens(self, tokens: int):
        self.tokens = tokens
        if self.is_busy:
            self.update_content()

    def set_custom_action(self, action_name: str):
        self.phrase = action_name
        self.update_content()

    def update_content(self) -> None:
        if not self.is_busy:
            return
            
        self.dots = (self.dots + 1) % 4
        dots_str = "." * self.dots + " " * (3 - self.dots)
        
        elapsed = int(time.time() - self.start_time)
        mins, secs = divmod(elapsed, 60)
        time_str = f"{mins}m {secs}s" if mins > 0 else f"{secs}s"
        
        # Мерцание (смена цвета)
        pulse_color = "#c678dd" if self.dots % 2 == 0 else "#e06c75"
        
        content = f"[bold {pulse_color}]⋮ {self.phrase}{dots_str}[/] [dim]({time_str} · ↓ {self.tokens} tokens · esc to cancel)[/]"
        self.update(content)

class LogosTUI(App):
    """Cline-inspired TUI for Logos ADK with glassmorphism."""
    
    CSS = """
    App {
        background: transparent;
    }

    Screen {
        background: transparent;
        layout: vertical;
    }

    #chat-area {
        height: 1fr;
        padding: 0 2;
        background: transparent;
    }

    #welcome-widget {
        height: 100%;
        align: center middle;
    }

    #logos-art {
        text-align: center;
        text-style: bold;
    }

    #welcome-text {
        text-align: center;
        color: #abb2bf;
        margin-top: 1;
    }

    #bottom-pane {
        height: auto;
        background: transparent;
    }

    #info-line {
        color: #c678dd;
        text-style: bold;
        padding: 0 1;
        margin-top: 1;
        margin-bottom: 1;
    }

    #input-group {
        border-top: solid #c678dd;
        border-bottom: solid #c678dd;
        height: auto;
        padding: 1 1;
        background: transparent;
    }
    
    #chat-input {
        border: none;
        background: transparent;
        color: #ffffff;
        height: auto;
        padding: 0 1;
    }

    .status-row {
        layout: horizontal;
        height: auto;
        padding: 1 1;
    }

    .left-status {
        width: 1fr;
        content-align: left middle;
        color: #5c6370;
    }

    .right-status {
        width: auto;
        content-align: right middle;
        color: #5c6370;
    }

    #yolo-status {
        color: #e06c75;
        text-style: bold;
    }

    .yolo-hint {
        color: #5c6370;
        text-style: none;
    }

    ActionWidget {
        margin: 1 0;
    }
    """

    BINDINGS = [
        Binding("ctrl+c", "quit", "Quit", show=True),
        Binding("ctrl+l", "clear_chat", "Clear", show=True),
    ]

    def __init__(self, config_path: str):
        super().__init__()
        self.config_path = config_path
        self._agent = None
        self.session_id = f"tui-{datetime.now().strftime('%H%M%S')}"
        self.model_name = "Agentic"
        self.tokens = "0 / 0"
        self.budget = "$0.000"

    async def on_mount(self) -> None:
        asyncio.create_task(self._initialize_agent())

    async def _initialize_agent(self) -> None:
        try:
            self._agent = await asyncio.to_thread(load_runnable_from_config, self.config_path)
            if hasattr(self._agent, "_config"):
                self.model_name = getattr(self._agent._config, "model", "Agentic")
            self._update_status_bar()
        except Exception as e:
            self.notify(f"Init Error: {e}")

    def _update_status_bar(self) -> None:
        try:
            self.query_one("#model-metrics", Label).update(f"{self.model_name} ████████ ({self.tokens}) | {self.budget}")
        except Exception:
            pass

    def compose(self) -> ComposeResult:
        yield ScrollableContainer(WelcomeWidget(), id="chat-area")
        
        with Vertical(id="bottom-pane"):
            yield StatusInfoLine(id="info-line")
            with Horizontal(id="input-group"):
                yield Label("[bold #e06c75]* [/]")
                yield Input(placeholder="Type your message or @path/to/file", id="chat-input")
            
            with Horizontal(classes="status-row"):
                yield Label("YOLO mode [dim](shift + tab to cycle)[/]", id="yolo-status", classes="left-status")
                yield Label("56.4% context used", classes="right-status")

    async def on_input_submitted(self, event: Input.Submitted) -> None:
        user_text = event.value.strip()
        if not user_text or self._agent is None:
            return

        event.input.value = ""
        chat_area = self.query_one("#chat-area")
        
        # Remove welcome widget
        welcome = chat_area.query(WelcomeWidget)
        if welcome:
            welcome.remove()

        chat_area.mount(MessageWidget(role="User", content=user_text))
        chat_area.scroll_end()

        info = self.query_one("#info-line", StatusInfoLine)
        info.start_action()

        response_content = ""
        agent_msg = MessageWidget(role="Agent", content="")
        chat_area.mount(agent_msg)

        try:
            async for chunk in self._agent.stream(user_text, session_id=self.session_id):
                if chunk.type == "text":
                    delta = getattr(chunk, "text", "") or getattr(chunk, "delta", "")
                    if delta:
                        response_content += delta
                        agent_msg.content = response_content
                        agent_msg.update(agent_msg.render())
                        chat_area.scroll_end()
                
                elif chunk.type == "tool_start":
                    t_name = getattr(chunk, "tool", "tool")
                    info.set_custom_action(f"Running {t_name}")
                    chat_area.mount(ActionWidget("Edit", f"Executing {t_name}...", icon="✓", color="#98c379"))
                    chat_area.scroll_end()
                
                elif chunk.type == "usage":
                    u = getattr(chunk, "usage", None)
                    if u:
                        self.tokens = f"{u.input_tokens} / {u.output_tokens}"
                        info.update_tokens(u.output_tokens)
                        self._update_status_bar()

            info.stop_action()
        except Exception as e:
            self.notify(f"Error: {e}", severity="error")
            info.stop_action()

    def action_clear_chat(self) -> None:
        chat_area = self.query_one("#chat-area")
        chat_area.query("*").remove()
        chat_area.mount(WelcomeWidget())
        self.notify("Session cleared")

if __name__ == "__main__":
    import sys
    config = sys.argv[1] if len(sys.argv) > 1 else "agent.yaml"
    app = LogosTUI(config)
    app.run()
