#!/opt/homebrew/opt/python@3.10/bin/python3.10
import sys
import asyncio
import json
import typer
import time
from typing import List, Optional
from pathlib import Path
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.live import Live
from rich.text import Text

from .delegator import run_sub_agent, auto_bundle_context
from .config import WORKSPACE_ROOT, AGENT_DIR, MEMORY_DIR

app = typer.Typer(
    name="subgemi",
    help="SUBGEMI: Gemini Sub-Agent Orchestration CLI (Parallel, Dashboard, Git-Review)",
    add_completion=False,
)
console = Console()

task_app = typer.Typer(help="Manage tasks and delegation.")
session_app = typer.Typer(help="Manage execution sessions.")

app.add_typer(task_app, name="task")
app.add_typer(session_app, name="session")

@task_app.command("delegate")
def delegate_task(
    prompt: str = typer.Argument(..., help="The instruction or task prompt for the sub-agent."),
    context_files: List[str] = typer.Option([], "--file", "-f", help="Specific files for context."),
    workflows: List[str] = typer.Option([], "--workflow", "-w", help="Workflows to include."),
    personas: List[str] = typer.Option([], "--persona", "-p", help="Personas to include."),
    repomix: List[str] = typer.Option([], "--repomix", "-x", help="Dirs to pack."),
    background: bool = typer.Option(True, "--background/--foreground", "-b", help="Run in background."),
    lane: str = typer.Option("default", "--lane", "-l", help="Execution lane."),
):
    """
    Delegate a task. Now defaults to background (Requirement 1: Parallelism).
    Will automatically trigger a git branch 'subgemi/<id>' for review (Requirement 3).
    """
    # 1. Preparation
    session_id = f"sub_{int(time.time())}"
    branch_name = f"subgemi/{session_id}"
    
    # Instruct the subagent to use git (Requirement 3)
    git_instruction = f"\n\nGIT WORKFLOW: You MUST create and work in a new branch named '{branch_name}'. DO NOT commit to 'main'."
    full_prompt = prompt + git_instruction

    with console.status("[bold green]Bundling context..."):
        bundled_context = auto_bundle_context(
            context_files=context_files,
            include_workflows=workflows,
            include_personas=personas,
            task_prompt=prompt
        )

    # 2. Execute
    try:
        result_json = asyncio.run(
            run_sub_agent(
                prompt=full_prompt,
                context_files=bundled_context,
                lane=lane,
                background=background,
                tmux=True,
                repomix_targets=repomix
            )
        )
        
        result = json.loads(result_json)
        
        if result.get("status") == "detached":
            console.print(Panel(
                f"[bold green]Parallel Task Dispatched[/bold green]\n"
                f"ID: [cyan]{result.get('session_id')}[/cyan]\n"
                f"Monitoring: [yellow]subgemi session board[/yellow]",
                title="SUBGEMI Sub-Agent"
            ))
        else:
            console.print(result)

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)

def generate_board():
    """Requirement 2: Dashboard Implementation"""
    registry_path = MEMORY_DIR / "sub_agent_registry.json"
    if not registry_path.exists():
        return Panel("No active sessions found.", title="Board")

    try:
        data = json.loads(registry_path.read_text())
        table = Table(title="SUBGEMI Sub-Agent Dashboard", expand=True)
        table.add_column("Session ID", style="cyan")
        table.add_column("Status", style="bold")
        table.add_column("Prompt", ratio=1)
        table.add_column("Time", style="magenta")
        table.add_column("Monitor", style="dim")

        for sid, info in sorted(data.items(), reverse=True)[:10]:
            status = info.get("status", "UNKNOWN")
            status_style = "green" if status == "COMPLETED" else "yellow" if status == "EXECUTING_PROCESS" else "red"
            
            table.add_row(
                sid,
                Text(status, style=status_style),
                info.get("prompt", ""),
                time.strftime("%H:%M:%S", time.localtime(info.get("start_time", 0))),
                f"tmux attach -t {info.get('tmux_session')}" if info.get('tmux_session') else "-"
            )
        return table
    except Exception as e:
        return Panel(f"Error: {e}", title="Error", border_style="red")

@session_app.command("board")
def board(refresh: int = typer.Option(2, "--refresh", "-r", help="Refresh interval in seconds.")):
    """Requirement 2: Live Dashboard (Manager Mode)"""
    with Live(generate_board(), refresh_per_second=1/refresh) as live:
        try:
            while True:
                time.sleep(refresh)
                live.update(generate_board())
        except KeyboardInterrupt:
            pass

@session_app.command("list")
def list_sessions():
    """Static list of sessions."""
    console.print(generate_board())

if __name__ == "__main__":
    app()
