#!/usr/bin/env python3
"""
Context Custodians - Vitruvyan Memory Warden CLI
"""

import sys
import argparse
import logging
from pathlib import Path

from .core.config import Config
from .core.state import StateManager
from .core.utils import setup_logging
from .agents.coordinator import CoordinatorAgent


class CLI:
    """Command Line Interface for Context Custodians"""

    def __init__(self):
        self.config = None
        self.state_manager = None
        self.coordinator = None

    def setup(self, workspace_path: str = None):
        """Setup CLI with configuration"""
        self.config = Config(workspace_path)
        self.state_manager = StateManager(self.config.config_dir)
        self.coordinator = CoordinatorAgent(self.config, self.state_manager)

    def init_command(self, args):
        """Initialize Context Custodians in workspace"""
        print("🤖 Initializing Context Custodians...")

        # Create .vmw directory
        vmw_dir = Path(self.config.workspace_path) / '.vmw'
        vmw_dir.mkdir(exist_ok=True)

        # Save initial config
        self.config.save_config()

        # Create initial context files
        self._create_initial_files()

        print(f"✅ Initialized in: {vmw_dir}")
        print("Run 'vmw start --daemon' to begin monitoring")

    def start_command(self, args):
        """Start the monitoring system"""
        if args.daemon:
            print("🤖 Starting Context Custodians in daemon mode...")
            self.coordinator.start_all_agents()
            print("✅ Monitoring active. Use 'vmw stop' to halt.")

            try:
                # Keep running
                import time
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                self.stop_command(args)
        else:
            print("🔍 Running one-time scan...")
            result = self.coordinator.execute()
            print(f"✅ Scan completed. Processed {result.get('agents_executed', 0)} agents.")

    def stop_command(self, args):
        """Stop the monitoring system"""
        print("🛑 Stopping Context Custodians...")
        self.coordinator.stop_all_agents()
        print("✅ All agents stopped.")

    def status_command(self, args):
        """Show system status"""
        print("📊 Context Custodians Status")
        print("=" * 40)

        # System health
        health = self.state_manager.get_system_health()
        print(f"🏥 System Health: {health}")

        # Agent status
        agent_status = self.coordinator.get_agent_status()
        print("\n🤖 Agents:")
        for agent_name, status in agent_status.items():
            enabled = self.config.is_agent_enabled(agent_name)
            running = status.get('running', False)
            last_status = status.get('status', {}).get('status', 'unknown')

            status_icon = "🟢" if running else "🔴"
            print(f"  {status_icon} {agent_name}: {last_status} ({'enabled' if enabled else 'disabled'})")

        # Recent activity
        last_scan = self.state_manager.get_last_scan()
        if last_scan:
            print(f"\n📅 Last Scan: {last_scan}")
        else:
            print("\n📅 Last Scan: Never")

        # Configuration
        print(f"\n⚙️  Monitored Files: {len(self.config.watched_files)}")
        print(f"⏱️  Scan Interval: {self.config.monitoring_interval} seconds")

    def scan_command(self, args):
        """Run a manual scan"""
        print("🔍 Running manual scan...")
        result = self.coordinator.execute()

        agents_executed = result.get('agents_executed', 0)
        print(f"✅ Manual scan completed. {agents_executed} agents executed.")

        if 'results' in result:
            for agent_name, agent_result in result['results'].items():
                if 'files_changed' in agent_result:
                    print(f"  📄 {agent_name}: {agent_result['files_changed']} files changed")

    def config_command(self, args):
        """Show or modify configuration"""
        if args.show:
            print("⚙️  Current Configuration:")
            print(self.config._config)
        elif args.set:
            key, value = args.set
            # Try to parse as JSON/int/bool
            try:
                import json
                parsed_value = json.loads(value)
            except:
                if value.lower() in ('true', 'false'):
                    parsed_value = value.lower() == 'true'
                elif value.isdigit():
                    parsed_value = int(value)
                else:
                    parsed_value = value

            self.config.set(key, parsed_value)
            print(f"✅ Set {key} = {parsed_value}")

    def install_service_command(self, args):
        """Install systemd service"""
        print("🔧 Installing systemd service...")

        service_content = self._generate_systemd_service()
        service_path = Path("/etc/systemd/system/vitruvyan-memory-warden.service")

        try:
            with open(service_path, 'w') as f:
                f.write(service_content)

            print("✅ Service file created")
            print("Run: sudo systemctl daemon-reload")
            print("Run: sudo systemctl enable vitruvyan-memory-warden")
            print("Run: sudo systemctl start vitruvyan-memory-warden")

        except PermissionError:
            print("❌ Permission denied. Run with sudo:")
            print(f"sudo tee {service_path} > /dev/null << 'EOF'")
            print(service_content)
            print("EOF")

    def uninstall_service_command(self, args):
        """Uninstall systemd service"""
        print("🔧 Uninstalling systemd service...")

        service_path = Path("/etc/systemd/system/vitruvyan-memory-warden.service")

        try:
            if service_path.exists():
                service_path.unlink()
                print("✅ Service file removed")
                print("Run: sudo systemctl daemon-reload")
            else:
                print("⚠️  Service file not found")
        except PermissionError:
            print("❌ Permission denied. Run: sudo rm /etc/systemd/system/vitruvyan-memory-warden.service")

    def _create_initial_files(self):
        """Create initial context files"""
        vmw_dir = Path(self.config.workspace_path) / '.vmw'

        # Create initial context file
        context_file = vmw_dir / self.config.get('output.context_file', 'ALWAYS_AVAILABLE_CONTEXT.md')
        initial_content = f"""# 🧠 AI Assistant Context
*Auto-generated: Initial setup*

## 📋 **Quick Status Overview**

🎯 **Project:** {Path(self.config.workspace_path).name}
🏗️ **Context System:** Initialized
📊 **Status:** Ready to monitor

---

## 🔄 **Vital Context Updates**

*Monitoring active - waiting for file changes*

---

*🎉 This context is automatically maintained and always current!*
"""

        with open(context_file, 'w') as f:
            f.write(initial_content)

    def _generate_systemd_service(self) -> str:
        """Generate systemd service file content"""
        workspace = self.config.workspace_path
        user = self.config.get('systemd.user', 'user')

        return f"""[Unit]
Description=Vitruvyan Memory Warden - Epistemic Context Guardian
After=network.target

[Service]
Type=simple
User={user}
WorkingDirectory={workspace}
ExecStart=/usr/bin/python3 -m vmw.cli start --daemon
ExecStop=/usr/bin/python3 -m vmw.cli stop
Restart=always
RestartSec=10
Environment=PATH=/usr/local/bin:/usr/bin:/bin

[Install]
WantedBy=multi-user.target
"""

    def run(self):
        """Main CLI entry point"""
        parser = argparse.ArgumentParser(
            description="Context Custodians - Vitruvyan Memory Warden",
            prog="vmw"
        )

        parser.add_argument(
            '--workspace', '-w',
            help='Workspace path (default: current directory)'
        )

        parser.add_argument(
            '--log-level', '-l',
            choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
            default='INFO',
            help='Logging level'
        )

        subparsers = parser.add_subparsers(dest='command', help='Commands')

        # init command
        subparsers.add_parser('init', help='Initialize Context Custodians in workspace')

        # start command
        start_parser = subparsers.add_parser('start', help='Start monitoring')
        start_parser.add_argument('--daemon', action='store_true', help='Run in background')

        # stop command
        subparsers.add_parser('stop', help='Stop monitoring')

        # status command
        subparsers.add_parser('status', help='Show system status')

        # scan command
        subparsers.add_parser('scan', help='Run manual scan')

        # config command
        config_parser = subparsers.add_parser('config', help='Configuration management')
        config_parser.add_argument('--show', action='store_true', help='Show current config')
        config_parser.add_argument('--set', nargs=2, metavar=('KEY', 'VALUE'), help='Set config value')

        # service commands
        subparsers.add_parser('install-service', help='Install systemd service')
        subparsers.add_parser('uninstall-service', help='Uninstall systemd service')

        args = parser.parse_args()

        if not args.command:
            parser.print_help()
            return

        # Setup logging
        setup_logging(args.log_level)

        # Setup system
        self.setup(args.workspace)

        # Execute command
        command_method = getattr(self, f"{args.command}_command", None)
        if command_method:
            command_method(args)
        else:
            print(f"❌ Unknown command: {args.command}")


def main():
    """Entry point"""
    cli = CLI()
    cli.run()


if __name__ == "__main__":
    main()