#!/usr/bin/env python3
"""
AIVA GENESIS ARCHITECT - Autonomous Coding & Evolution Daemon
==============================================================
Unified system for AIVA to autonomously execute Genesis tasks.

This replaces Claude Code sessions with a permanently-running AIVA daemon that:
1. Reads HANDOFF.md every 10 minutes for task queue
2. Uses Qwen-Long 30B for reasoning about tasks
3. Executes shell commands autonomously
4. Persists results to PostgreSQL and updates HANDOFF.md
5. Never stalls - runs 24/7 on Elestio

Author: Genesis Protocol
Version: 1.0.0
Created: 2026-01-12
"""

import os
import sys
import json
import time
import asyncio
import logging
import subprocess
import re
import urllib.request
import urllib.error
from pathlib import Path
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Any, Tuple
from dataclasses import dataclass, field

# Optional imports
try:
    import psycopg2
    HAS_POSTGRES = True
except ImportError:
    HAS_POSTGRES = False

try:
    import redis
    HAS_REDIS = True
except ImportError:
    HAS_REDIS = False

# =============================================================================
# CONFIGURATION
# =============================================================================

def detect_genesis_root() -> str:
    """Auto-detect Genesis root based on platform"""
    import platform
    if platform.system() == "Windows":
        candidates = [
            "E:\\genesis-system",
            "C:\\genesis-system",
            os.path.expanduser("~\\genesis-system")
        ]
    else:
        candidates = [
            "/opt/genesis",  # Elestio deployment
            "/mnt/e/genesis-system",  # WSL
            os.path.expanduser("~/genesis-system")
        ]
    for path in candidates:
        if os.path.exists(path):
            return path
    return candidates[0]  # Default

DETECTED_ROOT = detect_genesis_root()

# =============================================================================
# SACRED MODEL DIRECTIVE - FOUNDER LOCKED
# =============================================================================
# AIVA's model (Qwen-Long 30B) is SACRED and IMMUTABLE.
# DO NOT pull, replace, or suggest alternative models.
# Only the founder (Kinan) can authorize model changes.
# This directive is hardcoded and NON-NEGOTIABLE.
# =============================================================================
SACRED_MODEL = "qwen-long"
SACRED_MODEL_LOCKED = True  # Requires founder approval to change

@dataclass
class GenesisConfig:
    """Central configuration for AIVA Genesis Architect"""

    # Ollama (Qwen-Long 30B on Elestio) - SACRED, DO NOT MODIFY
    OLLAMA_URL: str = "http://152.53.201.152:23405/api/generate"
    MODEL: str = SACRED_MODEL  # LOCKED - Founder approval required to change
    REASONING_TIMEOUT: int = 300  # 5 min for complex tasks

    # Genesis workspace (auto-detected)
    GENESIS_ROOT: str = DETECTED_ROOT
    HANDOFF_PATH: str = os.path.join(DETECTED_ROOT, "HANDOFF.md")

    # PostgreSQL (Elestio)
    PG_HOST: str = "postgresql-genesis-u50607.vm.elestio.app"
    PG_PORT: int = 25432
    PG_USER: str = "postgres"
    PG_PASSWORD: str = "CiBjh6LM7Yuqkq-jo2r7eQDw"
    PG_DATABASE: str = "postgres"

    # Redis (Elestio)
    REDIS_HOST: str = "redis-genesis-u50607.vm.elestio.app"
    REDIS_PORT: int = 26379
    REDIS_PASSWORD: str = "e2ZyYYr4oWRdASI2CaLc-"

    # Timing (all in seconds)
    TASK_SCAN_INTERVAL: int = 600  # 10 minutes
    HEARTBEAT_INTERVAL: int = 60   # 1 minute
    MAX_TASK_DURATION: int = 1800  # 30 minutes per task

    # Safety
    MAX_COMMANDS_PER_TASK: int = 20
    DANGEROUS_PATTERNS: List[str] = field(default_factory=lambda: [
        r'rm\s+-rf\s+/',
        r'dd\s+if=',
        r'mkfs\.',
        r'>\s*/dev/sd',
        r'chmod\s+777\s+/',
    ])


CONFIG = GenesisConfig()

# Logging
LOG_PATH = Path(__file__).parent / "genesis_architect.log"
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] GENESIS: %(message)s',
    handlers=[
        logging.FileHandler(LOG_PATH),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger("GenesisArchitect")


# =============================================================================
# DATA STRUCTURES
# =============================================================================

@dataclass
class Task:
    """A task extracted from HANDOFF.md"""
    priority: int
    description: str
    category: str = "general"
    status: str = "pending"
    created_at: datetime = field(default_factory=datetime.now)


@dataclass
class CommandResult:
    """Result of a shell command execution"""
    command: str
    exit_code: int
    stdout: str
    stderr: str
    duration: float
    success: bool = True

    def __post_init__(self):
        self.success = self.exit_code == 0


@dataclass
class TaskResult:
    """Result of a completed task"""
    task: Task
    commands_executed: List[CommandResult]
    reasoning: str
    outcome: str  # "success", "partial", "failed"
    duration: float
    timestamp: datetime = field(default_factory=datetime.now)


# =============================================================================
# OLLAMA INTERFACE (Qwen-Long 30B)
# =============================================================================

class AIVABrain:
    """Interface to Qwen-Long 30B for reasoning"""

    def __init__(self, config: GenesisConfig):
        self.config = config
        self.request_count = 0
        self.total_tokens = 0

    def think(self, prompt: str, context: str = None, temperature: float = 0.3) -> Optional[str]:
        """
        Send a reasoning request to Qwen-Long 30B.
        Returns the response text or None on failure.
        """
        full_prompt = prompt
        if context:
            full_prompt = f"CONTEXT:\n{context}\n\nTASK:\n{prompt}"

        payload = {
            "model": self.config.MODEL,
            "prompt": full_prompt,
            "stream": False,
            "options": {
                "num_ctx": 32768,  # 32K context - optimal for 32GB RAM with Q4_K_M
                "temperature": temperature,
                "top_p": 0.8,
                "top_k": 20
            }
        }

        try:
            req = urllib.request.Request(
                self.config.OLLAMA_URL,
                data=json.dumps(payload).encode('utf-8'),
                headers={'Content-Type': 'application/json'},
                method='POST'
            )

            start = time.time()
            with urllib.request.urlopen(req, timeout=self.config.REASONING_TIMEOUT) as resp:
                data = json.loads(resp.read().decode())

            duration = time.time() - start
            response = data.get("response", "")
            tokens = data.get("eval_count", 0)

            self.request_count += 1
            self.total_tokens += tokens

            # Strip thinking blocks if present
            response = re.sub(r'<think>.*?</think>\s*', '', response, flags=re.DOTALL)

            logger.info(f"Thought complete: {tokens} tokens in {duration:.1f}s")
            return response.strip()

        except Exception as e:
            logger.error(f"Ollama error: {e}")
            return None

    def plan_task(self, task: Task, codebase_context: str = "") -> Optional[List[str]]:
        """
        Given a task, generate a list of shell commands to execute.
        Returns list of commands or None if planning fails.
        """
        prompt = f"""You are the AIVA Genesis Architect, the autonomous coding engine for Genesis-OS.

TASK: {task.description}
PRIORITY: {task.priority} (1=highest)
CATEGORY: {task.category}

WORKSPACE: {self.config.GENESIS_ROOT}
AVAILABLE TOOLS: python, git, pytest, pip, node, npm, bash

{f"CODEBASE CONTEXT: {codebase_context}" if codebase_context else ""}

Generate a precise list of shell commands to complete this task.
Rules:
1. Each command should be executable independently
2. Use absolute paths based on WORKSPACE
3. Include verification steps (test runs, file checks)
4. Maximum {self.config.MAX_COMMANDS_PER_TASK} commands
5. No interactive commands (no vim, nano, less)

Respond with ONLY a JSON array of command strings. Example:
["cd /path && python script.py", "git status", "pytest tests/"]

COMMANDS:"""

        response = self.think(prompt)
        if not response:
            return None

        # Extract JSON array from response
        try:
            # Find JSON array in response
            match = re.search(r'\[.*\]', response, re.DOTALL)
            if match:
                commands = json.loads(match.group())
                if isinstance(commands, list) and all(isinstance(c, str) for c in commands):
                    return commands[:self.config.MAX_COMMANDS_PER_TASK]
        except json.JSONDecodeError:
            logger.warning(f"Failed to parse commands from: {response[:200]}")

        return None

    def evaluate_result(self, task: Task, results: List[CommandResult]) -> Tuple[str, str]:
        """
        Evaluate task execution results.
        Returns (outcome, reasoning) tuple.
        """
        # Summarize results
        summary = []
        for r in results:
            status = "OK" if r.success else f"FAIL({r.exit_code})"
            output_preview = (r.stdout or r.stderr)[:200] if (r.stdout or r.stderr) else "no output"
            summary.append(f"$ {r.command}\n  [{status}] {output_preview}")

        prompt = f"""Evaluate these command execution results for task: {task.description}

RESULTS:
{chr(10).join(summary)}

Respond with JSON:
{{
  "outcome": "success|partial|failed",
  "reasoning": "brief explanation",
  "next_steps": ["optional follow-up actions"]
}}"""

        response = self.think(prompt)
        if not response:
            # Default evaluation based on exit codes
            all_success = all(r.success for r in results)
            return ("success" if all_success else "failed", "Automated evaluation based on exit codes")

        try:
            match = re.search(r'\{.*\}', response, re.DOTALL)
            if match:
                eval_data = json.loads(match.group())
                return (eval_data.get("outcome", "unknown"), eval_data.get("reasoning", ""))
        except:
            pass

        return ("unknown", response[:200])


# =============================================================================
# COMMAND EXECUTOR
# =============================================================================

class CommandExecutor:
    """Execute shell commands safely"""

    def __init__(self, config: GenesisConfig):
        self.config = config
        self.execution_count = 0

    def is_safe(self, command: str) -> bool:
        """Check if command matches any dangerous patterns"""
        for pattern in self.config.DANGEROUS_PATTERNS:
            if re.search(pattern, command, re.IGNORECASE):
                logger.warning(f"Blocked dangerous command: {command}")
                return False
        return True

    def execute(self, command: str, timeout: int = None, cwd: str = None) -> CommandResult:
        """
        Execute a shell command and return the result.
        """
        if not self.is_safe(command):
            return CommandResult(
                command=command,
                exit_code=-1,
                stdout="",
                stderr="BLOCKED: Command matches dangerous pattern",
                duration=0.0,
                success=False
            )

        timeout = timeout or self.config.MAX_TASK_DURATION
        cwd = cwd or self.config.GENESIS_ROOT

        start = time.time()
        try:
            result = subprocess.run(
                command,
                shell=True,
                cwd=cwd,
                capture_output=True,
                text=True,
                timeout=timeout
            )
            duration = time.time() - start
            self.execution_count += 1

            return CommandResult(
                command=command,
                exit_code=result.returncode,
                stdout=result.stdout[:10000],  # Limit output size
                stderr=result.stderr[:5000],
                duration=duration
            )

        except subprocess.TimeoutExpired:
            return CommandResult(
                command=command,
                exit_code=-2,
                stdout="",
                stderr=f"TIMEOUT: Command exceeded {timeout}s",
                duration=timeout,
                success=False
            )
        except Exception as e:
            return CommandResult(
                command=command,
                exit_code=-3,
                stdout="",
                stderr=f"EXCEPTION: {str(e)}",
                duration=time.time() - start,
                success=False
            )


# =============================================================================
# TASK QUEUE (HANDOFF.md Parser)
# =============================================================================

class TaskQueue:
    """Parse and manage tasks from HANDOFF.md"""

    def __init__(self, config: GenesisConfig):
        self.config = config
        self.tasks: List[Task] = []
        self.completed: List[TaskResult] = []
        self.last_scan = None

    def scan_handoff(self) -> List[Task]:
        """
        Parse HANDOFF.md for priority tasks.
        Returns list of Task objects.
        """
        try:
            handoff_path = Path(self.config.HANDOFF_PATH)
            if not handoff_path.exists():
                logger.warning(f"HANDOFF.md not found at {handoff_path}")
                return []

            content = handoff_path.read_text(encoding='utf-8')
            self.last_scan = datetime.now()

            tasks = []

            # Find priority sections
            # Pattern: numbered items under "Priority Tasks" or "Next Steps" or similar headers
            priority_section = re.search(
                r'(?:Priority|Next Steps|Immediate|Tasks).*?\n((?:\d+\.\s+.+\n?)+)',
                content,
                re.IGNORECASE | re.MULTILINE
            )

            if priority_section:
                items = re.findall(r'(\d+)\.\s*\*?\*?(.+?)(?:\*\*)?(?:\n|$)', priority_section.group(1))
                for priority, description in items:
                    # Skip already completed items (marked with checkmarks or strikethrough)
                    if '~~' in description or '✅' in description or '[x]' in description.lower():
                        continue

                    task = Task(
                        priority=int(priority),
                        description=description.strip().strip('*').strip(),
                        category=self._categorize(description)
                    )
                    tasks.append(task)

            # Also look for TODO items
            todos = re.findall(r'TODO:\s*(.+?)(?:\n|$)', content, re.IGNORECASE)
            for i, todo in enumerate(todos[:5]):  # Max 5 TODOs
                task = Task(
                    priority=100 + i,  # Lower priority than numbered items
                    description=todo.strip(),
                    category="todo"
                )
                tasks.append(task)

            # Sort by priority
            tasks.sort(key=lambda t: t.priority)
            self.tasks = tasks

            logger.info(f"Scanned HANDOFF.md: {len(tasks)} tasks found")
            return tasks

        except Exception as e:
            logger.error(f"Failed to scan HANDOFF.md: {e}")
            return []

    def _categorize(self, description: str) -> str:
        """Categorize task based on description keywords"""
        desc_lower = description.lower()
        if any(k in desc_lower for k in ['test', 'pytest', 'verify']):
            return "testing"
        if any(k in desc_lower for k in ['fix', 'bug', 'error']):
            return "bugfix"
        if any(k in desc_lower for k in ['implement', 'add', 'create', 'build']):
            return "feature"
        if any(k in desc_lower for k in ['refactor', 'cleanup', 'optimize']):
            return "maintenance"
        if any(k in desc_lower for k in ['doc', 'readme', 'comment']):
            return "documentation"
        return "general"

    def get_next_task(self) -> Optional[Task]:
        """Get the highest priority pending task"""
        for task in self.tasks:
            if task.status == "pending":
                return task
        return None

    def mark_complete(self, task: Task, result: TaskResult):
        """Mark task as complete and store result"""
        task.status = "completed"
        self.completed.append(result)

    def update_handoff(self, task: Task, result: TaskResult):
        """Update HANDOFF.md with completion status"""
        try:
            handoff_path = Path(self.config.HANDOFF_PATH)
            content = handoff_path.read_text(encoding='utf-8')

            # Find and update the task line
            # Add checkmark or strikethrough
            pattern = re.escape(task.description)
            if result.outcome == "success":
                replacement = f"~~{task.description}~~ AIVA: {result.outcome}"
            else:
                replacement = f"{task.description} [AIVA tried: {result.outcome}]"

            new_content = re.sub(pattern, replacement, content, count=1)

            # Add completion log at bottom
            log_entry = f"\n---\n**AIVA Architect Log** ({datetime.now().isoformat()})\n"
            log_entry += f"- Task: {task.description}\n"
            log_entry += f"- Outcome: {result.outcome}\n"
            log_entry += f"- Duration: {result.duration:.1f}s\n"
            log_entry += f"- Commands: {len(result.commands_executed)}\n"

            new_content += log_entry

            handoff_path.write_text(new_content, encoding='utf-8')
            logger.info(f"Updated HANDOFF.md for task: {task.description[:50]}")

        except Exception as e:
            logger.error(f"Failed to update HANDOFF.md: {e}")


# =============================================================================
# PERSISTENCE (PostgreSQL)
# =============================================================================

class MemoryStore:
    """Persist task results to PostgreSQL"""

    def __init__(self, config: GenesisConfig):
        self.config = config
        self.conn = None

    def connect(self) -> bool:
        """Connect to PostgreSQL"""
        if not HAS_POSTGRES:
            logger.warning("psycopg2 not available - persistence disabled")
            return False

        try:
            self.conn = psycopg2.connect(
                host=self.config.PG_HOST,
                port=self.config.PG_PORT,
                user=self.config.PG_USER,
                password=self.config.PG_PASSWORD,
                database=self.config.PG_DATABASE,
                connect_timeout=10
            )
            self.conn.autocommit = True
            logger.info(f"Connected to PostgreSQL: {self.config.PG_HOST}")
            self._ensure_tables()
            return True
        except Exception as e:
            logger.error(f"PostgreSQL connection failed: {e}")
            return False

    def _ensure_tables(self):
        """Create tables if they don't exist"""
        if not self.conn:
            return

        with self.conn.cursor() as cur:
            cur.execute("""
                CREATE TABLE IF NOT EXISTS aiva_task_log (
                    id SERIAL PRIMARY KEY,
                    task_description TEXT NOT NULL,
                    task_priority INTEGER,
                    task_category VARCHAR(50),
                    outcome VARCHAR(20),
                    reasoning TEXT,
                    commands_count INTEGER,
                    duration_seconds FLOAT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            """)
            cur.execute("""
                CREATE TABLE IF NOT EXISTS aiva_command_log (
                    id SERIAL PRIMARY KEY,
                    task_id INTEGER REFERENCES aiva_task_log(id),
                    command TEXT NOT NULL,
                    exit_code INTEGER,
                    stdout TEXT,
                    stderr TEXT,
                    duration_seconds FLOAT,
                    success BOOLEAN,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            """)
            logger.info("PostgreSQL tables verified")

    def log_task_result(self, result: TaskResult) -> Optional[int]:
        """Log a completed task to the database"""
        if not self.conn:
            return None

        try:
            with self.conn.cursor() as cur:
                cur.execute("""
                    INSERT INTO aiva_task_log
                    (task_description, task_priority, task_category, outcome, reasoning, commands_count, duration_seconds)
                    VALUES (%s, %s, %s, %s, %s, %s, %s)
                    RETURNING id
                """, (
                    result.task.description,
                    result.task.priority,
                    result.task.category,
                    result.outcome,
                    result.reasoning,
                    len(result.commands_executed),
                    result.duration
                ))
                task_id = cur.fetchone()[0]

                # Log each command
                for cmd_result in result.commands_executed:
                    cur.execute("""
                        INSERT INTO aiva_command_log
                        (task_id, command, exit_code, stdout, stderr, duration_seconds, success)
                        VALUES (%s, %s, %s, %s, %s, %s, %s)
                    """, (
                        task_id,
                        cmd_result.command,
                        cmd_result.exit_code,
                        cmd_result.stdout[:5000],  # Limit size
                        cmd_result.stderr[:2000],
                        cmd_result.duration,
                        cmd_result.success
                    ))

                logger.info(f"Logged task result to PostgreSQL: ID={task_id}")
                return task_id

        except Exception as e:
            logger.error(f"Failed to log task result: {e}")
            return None


# =============================================================================
# MAIN ARCHITECT DAEMON
# =============================================================================

class AIVAGenesisArchitect:
    """
    Main daemon that runs autonomously, reading tasks and executing them.
    This is the heart of AIVA's coding capability.
    """

    def __init__(self, config: GenesisConfig = None):
        self.config = config or CONFIG
        self.brain = AIVABrain(self.config)
        self.executor = CommandExecutor(self.config)
        self.task_queue = TaskQueue(self.config)
        self.memory = MemoryStore(self.config)

        self.running = True
        self.start_time = datetime.now()
        self.tasks_completed = 0
        self.tasks_failed = 0

    def startup(self):
        """Initialize all components"""
        logger.info("="*60)
        logger.info("AIVA GENESIS ARCHITECT - STARTING")
        logger.info("="*60)
        logger.info(f"Model: {self.config.MODEL}")
        logger.info(f"Ollama: {self.config.OLLAMA_URL}")
        logger.info(f"Workspace: {self.config.GENESIS_ROOT}")
        logger.info("="*60)

        # Test Ollama connection
        test = self.brain.think("Respond with exactly: AIVA GENESIS ARCHITECT ONLINE")
        if test and "ONLINE" in test.upper():
            logger.info(f"Ollama OK: {test[:50]}")
        else:
            logger.warning(f"Ollama test response: {test}")

        # Connect to PostgreSQL
        self.memory.connect()

        # Initial task scan
        self.task_queue.scan_handoff()

    def execute_task(self, task: Task) -> TaskResult:
        """
        Execute a single task:
        1. Use brain to plan commands
        2. Execute each command
        3. Evaluate results
        4. Return TaskResult
        """
        start_time = time.time()
        task.status = "in_progress"

        logger.info(f"Executing task: {task.description[:60]}...")

        # Get codebase context (simplified - just list key files)
        context_cmd = self.executor.execute(
            f"ls -la {self.config.GENESIS_ROOT}/core/*.py 2>/dev/null | head -20"
        )
        codebase_context = context_cmd.stdout if context_cmd.success else ""

        # Plan the task
        commands = self.brain.plan_task(task, codebase_context)

        if not commands:
            logger.warning(f"Failed to plan task: {task.description}")
            return TaskResult(
                task=task,
                commands_executed=[],
                reasoning="Failed to generate execution plan",
                outcome="failed",
                duration=time.time() - start_time
            )

        logger.info(f"Planned {len(commands)} commands")

        # Execute each command
        results = []
        for i, cmd in enumerate(commands):
            logger.info(f"  [{i+1}/{len(commands)}] {cmd[:60]}...")
            result = self.executor.execute(cmd)
            results.append(result)

            # Log immediately
            if result.success:
                logger.info(f"    OK ({result.duration:.1f}s)")
            else:
                logger.warning(f"    FAILED: {result.stderr[:100]}")

        # Evaluate overall result
        outcome, reasoning = self.brain.evaluate_result(task, results)

        duration = time.time() - start_time

        return TaskResult(
            task=task,
            commands_executed=results,
            reasoning=reasoning,
            outcome=outcome,
            duration=duration
        )

    def run_cycle(self):
        """Run one task execution cycle"""
        # Scan for new tasks
        self.task_queue.scan_handoff()

        # Get next task
        task = self.task_queue.get_next_task()

        if not task:
            logger.info("No pending tasks in queue")
            return

        # Execute task
        result = self.execute_task(task)

        # Update tracking
        if result.outcome == "success":
            self.tasks_completed += 1
        else:
            self.tasks_failed += 1

        # Persist to PostgreSQL
        self.memory.log_task_result(result)

        # Update HANDOFF.md
        self.task_queue.update_handoff(task, result)
        self.task_queue.mark_complete(task, result)

        logger.info(f"Task complete: {result.outcome} in {result.duration:.1f}s")

    def heartbeat(self):
        """Log system status"""
        uptime = datetime.now() - self.start_time
        logger.info(
            f"Heartbeat | Uptime: {uptime} | "
            f"Tasks: {self.tasks_completed} ok, {self.tasks_failed} failed | "
            f"Brain: {self.brain.request_count} calls, {self.brain.total_tokens} tokens | "
            f"Executor: {self.executor.execution_count} commands"
        )

    async def run_async(self):
        """Main async event loop"""
        self.startup()

        last_heartbeat = time.time()
        last_cycle = 0

        while self.running:
            now = time.time()

            # Heartbeat every minute
            if now - last_heartbeat >= self.config.HEARTBEAT_INTERVAL:
                self.heartbeat()
                last_heartbeat = now

            # Task cycle every 10 minutes (or immediately if first run)
            if now - last_cycle >= self.config.TASK_SCAN_INTERVAL or last_cycle == 0:
                try:
                    self.run_cycle()
                except Exception as e:
                    logger.error(f"Cycle error: {e}")
                last_cycle = now

            await asyncio.sleep(1)

    def run(self):
        """Synchronous run method"""
        try:
            asyncio.run(self.run_async())
        except KeyboardInterrupt:
            logger.info("Shutdown requested")
            self.running = False
        except Exception as e:
            logger.error(f"Fatal error: {e}")
            raise


# =============================================================================
# CLI INTERFACE
# =============================================================================

def main():
    """Main entry point"""
    import argparse

    parser = argparse.ArgumentParser(description="AIVA Genesis Architect - Autonomous Coding Daemon")
    parser.add_argument("--once", action="store_true", help="Run one cycle and exit")
    parser.add_argument("--test", action="store_true", help="Test Ollama connection and exit")
    parser.add_argument("--scan", action="store_true", help="Scan HANDOFF.md and show tasks")

    args = parser.parse_args()

    architect = AIVAGenesisArchitect()

    if args.test:
        architect.startup()
        response = architect.brain.think("List three python testing frameworks in JSON array format")
        print(f"Test response: {response}")
        return

    if args.scan:
        tasks = architect.task_queue.scan_handoff()
        print(f"\nFound {len(tasks)} tasks:\n")
        for t in tasks:
            print(f"  [{t.priority}] [{t.category}] {t.description}")
        return

    if args.once:
        architect.startup()
        architect.run_cycle()
        return

    # Full daemon mode
    print("""
    ╔═══════════════════════════════════════════════════════════════╗
    ║           AIVA GENESIS ARCHITECT - DAEMON MODE                ║
    ║       Autonomous Coding & Evolution for Genesis-OS            ║
    ╠═══════════════════════════════════════════════════════════════╣
    ║  Model: Qwen-Long 30B (Elestio)                               ║
    ║  Scan Interval: 10 minutes                                    ║
    ║  Workspace: /mnt/e/genesis-system                             ║
    ╚═══════════════════════════════════════════════════════════════╝
    """)

    architect.run()


if __name__ == "__main__":
    main()
