"""Simple TUI for emdash - bottom input, scrolling log above."""

import asyncio
from textual.app import App, ComposeResult
from textual.containers import ScrollableContainer, Container
from textual.widgets import Input, Static, RichLog
from textual.binding import Binding
from rich.text import Text
from rich.markdown import Markdown


class EmdashApp(App):
    """Minimal TUI with bottom input and scrolling log."""

    CSS = """
    Screen {
        background: #0d0d0d;
    }

    #log-container {
        height: 1fr;
        border: none;
        padding: 0 1;
    }

    #log {
        background: #0d0d0d;
        color: #e8e8e8;
        scrollbar-color: #333333;
        scrollbar-color-hover: #555555;
        scrollbar-color-active: #777777;
    }

    #input-container {
        height: auto;
        max-height: 5;
        dock: bottom;
        padding: 0 1;
        background: #0d0d0d;
    }

    #separator {
        height: 1;
        background: #1a1a1a;
        color: #333333;
        text-style: dim;
    }

    #prompt-input {
        background: #0d0d0d;
        border: none;
        padding: 0;
        color: #e8e8e8;
    }

    #prompt-input:focus {
        border: none;
    }

    #prompt-input > .input--placeholder {
        color: #555555;
    }

    #status-bar {
        height: 1;
        background: #1a1a1a;
        color: #666666;
        padding: 0 1;
        dock: bottom;
    }
    """

    BINDINGS = [
        Binding("ctrl+c", "quit", "Quit", show=False),
        Binding("escape", "quit", "Quit", show=False),
    ]

    def __init__(self, on_submit=None, model: str = "claude-sonnet-4", **kwargs):
        """Initialize the TUI.

        Args:
            on_submit: Async callback(message) -> AsyncIterator[event]
            model: Model name to display
        """
        super().__init__(**kwargs)
        self._on_submit = on_submit
        self._model = model
        self._processing = False

    def compose(self) -> ComposeResult:
        """Create the UI layout."""
        # Log area (scrollable)
        with ScrollableContainer(id="log-container"):
            yield RichLog(id="log", highlight=True, markup=True, wrap=True)

        # Separator line
        yield Static("─" * 200, id="separator")

        # Input area
        with Container(id="input-container"):
            yield Input(
                placeholder="Ask anything... (Ctrl+C to quit)",
                id="prompt-input",
            )

        # Status bar
        yield Static(f"  model: {self._model}  │  mode: code", id="status-bar")

    def on_mount(self) -> None:
        """Focus the input on startup."""
        self.query_one("#prompt-input", Input).focus()
        # Welcome message
        log = self.query_one("#log", RichLog)
        log.write(Text("─── emdash ───", style="dim"))
        log.write("")

    async def on_input_submitted(self, event: Input.Submitted) -> None:
        """Handle input submission."""
        message = event.value.strip()
        if not message:
            return

        # Clear input
        event.input.value = ""

        # Don't allow multiple concurrent requests
        if self._processing:
            return

        self._processing = True
        log = self.query_one("#log", RichLog)

        # Show user message
        log.write("")
        log.write(Text(f"› {message}", style="bold #f0a0a0"))
        log.write("")

        if self._on_submit:
            try:
                # Call the async handler and stream results
                async for event_data in self._on_submit(message):
                    self._handle_event(log, event_data)
            except Exception as e:
                log.write(Text(f"Error: {e}", style="red"))
        else:
            # Demo mode - just echo
            log.write(Text("(No handler connected)", style="dim"))

        self._processing = False
        log.write("")

    def _handle_event(self, log: RichLog, event: dict) -> None:
        """Handle an SSE event and render it."""
        event_type = event.get("type", "")
        data = event.get("data", {})

        if event_type == "thinking":
            content = data.get("content", data.get("message", ""))
            if content:
                # Show thinking in muted style
                for line in content.split("\n")[:3]:  # First 3 lines
                    if line.strip():
                        log.write(Text(f"  {line[:100]}", style="dim"))

        elif event_type == "tool_start":
            name = data.get("name", "")
            args = data.get("args", {})
            # Format args nicely
            arg_str = ""
            if "path" in args:
                arg_str = str(args["path"])
            elif "pattern" in args:
                arg_str = str(args["pattern"])
            elif "query" in args:
                arg_str = str(args["query"])
            elif "command" in args:
                arg_str = str(args["command"])[:50]

            if arg_str:
                log.write(Text(f"  ◦ {name}", style="#d4a574") + Text(f" {arg_str}", style="dim"))
            else:
                log.write(Text(f"  ◦ {name}", style="#d4a574"))

        elif event_type == "tool_result":
            name = data.get("name", "")
            success = data.get("success", True)
            icon = "▸" if success else "✗"
            style = "#7a9f7a" if success else "red"
            log.write(Text(f"  {icon} {name}", style=style))

        elif event_type == "response":
            content = data.get("content", "")
            if content:
                log.write("")
                # Render as markdown
                try:
                    log.write(Markdown(content))
                except Exception:
                    log.write(Text(content))

        elif event_type == "partial_response":
            # For streaming - we'll batch these
            pass

        elif event_type == "error":
            msg = data.get("message", "Unknown error")
            log.write(Text(f"  ✗ Error: {msg}", style="red"))

        elif event_type == "subagent_start":
            agent_type = data.get("agent_type", "Agent")
            prompt = data.get("prompt", "")[:60]
            log.write("")
            log.write(Text(f"  ┌─ {agent_type} Agent", style="#d4a574"))
            if prompt:
                log.write(Text(f"  │  {prompt}...", style="dim"))

        elif event_type == "subagent_end":
            agent_type = data.get("agent_type", "Agent")
            success = data.get("success", True)
            icon = "✓" if success else "✗"
            style = "#7a9f7a" if success else "red"
            log.write(Text(f"  └─ {icon} {agent_type} done", style=style))
            log.write("")

    def action_quit(self) -> None:
        """Quit the application."""
        self.exit()


def run_tui(on_submit=None, model: str = "claude-sonnet-4"):
    """Run the TUI app.

    Args:
        on_submit: Async callback(message) -> AsyncIterator[event]
        model: Model name to display
    """
    app = EmdashApp(on_submit=on_submit, model=model)
    app.run()


if __name__ == "__main__":
    # Demo mode
    async def demo_handler(message):
        """Demo handler that echoes back."""
        yield {"type": "thinking", "data": {"content": f"Processing: {message}"}}
        await asyncio.sleep(0.5)
        yield {"type": "tool_start", "data": {"name": "read_file", "args": {"path": "example.py"}}}
        await asyncio.sleep(0.3)
        yield {"type": "tool_result", "data": {"name": "read_file", "success": True}}
        await asyncio.sleep(0.3)
        yield {"type": "response", "data": {"content": f"You said: **{message}**\n\nThis is a demo response."}}

    run_tui(on_submit=demo_handler)
