#!/usr/bin/env python3
"""
Genesis Aider Dispatcher
Dispatches coding tasks to Aider running on AIVA's Elestio server.

Usage:
    python aider_dispatcher.py "Create a function that validates email addresses"
    python aider_dispatcher.py --file tasks.txt  # One task per line
"""

import subprocess
import sys
import argparse
from pathlib import Path
from datetime import datetime

# Elestio SSH config (uses ~/.ssh/config 'aiva' host)
SSH_HOST = "aiva"
AIDER_WORKER = "/root/genesis-aider/aider_worker.sh"
WORKSPACE = "/root/genesis-aider/workspace"


def dispatch_task(task: str, workspace: str = WORKSPACE) -> dict:
    """
    Dispatch a coding task to Aider on Elestio.

    Args:
        task: The coding task description
        workspace: Working directory on Elestio

    Returns:
        dict with status, output, and duration
    """
    start = datetime.now()

    cmd = [
        "ssh", SSH_HOST,
        f"cd {workspace} && /root/genesis-aider/aider_worker.sh '{task}' '{workspace}'"
    ]

    print(f"[DISPATCH] Task: {task[:80]}...")
    print(f"[DISPATCH] Workspace: {workspace}")

    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=600  # 10 minute timeout
        )

        duration = (datetime.now() - start).total_seconds()

        return {
            "status": "success" if result.returncode == 0 else "failed",
            "output": result.stdout,
            "error": result.stderr,
            "duration": duration,
            "task": task
        }

    except subprocess.TimeoutExpired:
        return {
            "status": "timeout",
            "output": "",
            "error": "Task timed out after 600 seconds",
            "duration": 600,
            "task": task
        }
    except Exception as e:
        return {
            "status": "error",
            "output": "",
            "error": str(e),
            "duration": (datetime.now() - start).total_seconds(),
            "task": task
        }


def main():
    parser = argparse.ArgumentParser(description="Dispatch tasks to Aider on Elestio")
    parser.add_argument("task", nargs="?", help="Task description")
    parser.add_argument("--file", "-f", help="File with tasks (one per line)")
    parser.add_argument("--workspace", "-w", default=WORKSPACE, help="Workspace directory")

    args = parser.parse_args()

    if args.file:
        # Process multiple tasks from file
        tasks = Path(args.file).read_text().strip().split("\n")
        for i, task in enumerate(tasks, 1):
            if task.strip():
                print(f"\n=== Task {i}/{len(tasks)} ===")
                result = dispatch_task(task.strip(), args.workspace)
                print(f"Status: {result['status']}")
                print(f"Duration: {result['duration']:.1f}s")
                if result['error']:
                    print(f"Error: {result['error'][:200]}")
    elif args.task:
        # Single task
        result = dispatch_task(args.task, args.workspace)
        print(f"\nStatus: {result['status']}")
        print(f"Duration: {result['duration']:.1f}s")
        print(f"\nOutput:\n{result['output']}")
        if result['error']:
            print(f"\nErrors:\n{result['error']}")
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
