#!/usr/bin/env python3
"""
DevMon - Development Service Monitor CLI
Manage development services with auto-stop capabilities
"""

import argparse
import subprocess
import sys
import json
import os
from typing import Dict, List, Tuple
from datetime import datetime

# Add src directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
try:
    from monkey_monitor_common import get_mcp_processes, MCP_PATTERNS
    MCP_SUPPORT = True
except ImportError:
    MCP_SUPPORT = False

from monkey_pc_client import (ControlError, quner_policy_display,
                              request as pc_request, status as pc_status)

# Service definitions
SERVICES = {
    'mysql': {
        'service': 'mysql.service',
        'monitor': 'mysql-idle-monitor.service',
        'port': 3306,
        'description': 'MySQL Database Server'
    },
    'docker': {
        'service': 'docker.service',
        'description': 'Docker Container Engine'
    },
    'postgresql': {
        'service': 'postgresql.service',
        'port': 5432,
        'description': 'PostgreSQL Database Server'
    },
}


class Colors:
    """ANSI color codes"""
    RESET = '\033[0m'
    BOLD = '\033[1m'
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    CYAN = '\033[96m'
    GRAY = '\033[90m'


def run_cmd(cmd: List[str], capture=True) -> Tuple[int, str, str]:
    """Run a shell command and return (returncode, stdout, stderr)"""
    try:
        if capture:
            result = subprocess.run(cmd, capture_output=True, text=True)
            return result.returncode, result.stdout, result.stderr
        else:
            result = subprocess.run(cmd)
            return result.returncode, '', ''
    except Exception as e:
        return 1, '', str(e)


def get_service_status(service_name: str) -> Dict:
    """Get detailed status of a systemd service"""
    ret, out, err = run_cmd(['systemctl', 'show', service_name,
                             '--no-pager',
                             '-p', 'ActiveState',
                             '-p', 'SubState',
                             '-p', 'MemoryCurrent',
                             '-p', 'MemoryPeak',
                             '-p', 'MainPID',
                             '-p', 'LoadState'])

    status = {}
    for line in out.split('\n'):
        if '=' in line:
            key, value = line.split('=', 1)
            status[key] = value

    # Parse memory (convert from bytes to MB)
    # Handle '[not set]' and other non-numeric values
    try:
        mem_current = int(status.get('MemoryCurrent', '0'))
    except ValueError:
        mem_current = 0

    try:
        mem_peak = int(status.get('MemoryPeak', '0'))
    except ValueError:
        mem_peak = 0

    return {
        'active': status.get('ActiveState', 'unknown'),
        'sub': status.get('SubState', 'unknown'),
        'memory_mb': mem_current / 1024 / 1024 if mem_current > 0 else 0,
        'memory_peak_mb': mem_peak / 1024 / 1024 if mem_peak > 0 else 0,
        'pid': int(status.get('MainPID', '0')),
        'loaded': status.get('LoadState', 'unknown')
    }


def get_connection_count(port: int) -> int:
    """Get number of active connections to a port"""
    ret, out, err = run_cmd(['ss', '-tn'])
    if ret != 0:
        return -1

    count = 0
    for line in out.split('\n'):
        if f':{port}' in line and 'ESTAB' in line:
            count += 1
    return count


def format_memory(mb: float) -> str:
    """Format memory in MB with color coding"""
    if mb == 0:
        return f"{Colors.GRAY}0 MB{Colors.RESET}"
    elif mb < 100:
        return f"{Colors.GREEN}{mb:.1f} MB{Colors.RESET}"
    elif mb < 500:
        return f"{Colors.YELLOW}{mb:.1f} MB{Colors.RESET}"
    else:
        return f"{Colors.RED}{mb:.1f} MB{Colors.RESET}"


def format_status(active: str, sub: str) -> str:
    """Format service status with colors"""
    if active == 'active':
        return f"{Colors.GREEN}●{Colors.RESET} {Colors.BOLD}running{Colors.RESET}"
    elif active == 'inactive':
        return f"{Colors.GRAY}○{Colors.RESET} stopped"
    elif active == 'failed':
        return f"{Colors.RED}✗{Colors.RESET} {Colors.RED}failed{Colors.RESET}"
    else:
        return f"{Colors.YELLOW}?{Colors.RESET} {active}"


def cmd_status(args):
    """Show status of all managed services"""
    print(f"\n{Colors.BOLD}DevMon - Service Status{Colors.RESET}")
    print(f"{Colors.GRAY}{'─' * 80}{Colors.RESET}\n")

    for name, config in SERVICES.items():
        service = config['service']
        status = get_service_status(service)

        # Get monitor status if exists
        monitor_status = ""
        if 'monitor' in config:
            mon_stat = get_service_status(config['monitor'])
            if mon_stat['active'] == 'active':
                monitor_status = f"{Colors.CYAN}(monitored){Colors.RESET}"

        # Get connection count if service is running
        connections = ""
        if status['active'] == 'active' and 'port' in config:
            conn_count = get_connection_count(config['port'])
            if conn_count >= 0:
                if conn_count == 0:
                    connections = f" {Colors.GRAY}[no connections]{Colors.RESET}"
                else:
                    connections = f" {Colors.GREEN}[{conn_count} conn]{Colors.RESET}"

        # Print service info
        status_str = format_status(status['active'], status['sub'])
        mem_str = format_memory(status['memory_mb'])

        print(f"{Colors.BOLD}{name:12}{Colors.RESET} {status_str:30} {mem_str:20} {monitor_status}{connections}")
        print(f"             {Colors.GRAY}{config['description']}{Colors.RESET}")
        print()

    # Show MCP processes if supported
    if MCP_SUPPORT:
        mcps = get_mcp_processes()
        if mcps:
            print(f"{Colors.BOLD}MCP SERVERS{Colors.RESET}")
            print(f"{Colors.GRAY}{'─' * 80}{Colors.RESET}\n")

            for name, info in mcps.items():
                pattern = MCP_PATTERNS.get(name, {})
                desc = pattern.get('description', 'Unknown MCP')
                count = info.get('count', 1)
                instances = f" ({count} instances)" if count > 1 else ""

                mem_str = format_memory(info['memory_mb'])
                status_str = f"{Colors.GREEN}●{Colors.RESET} {Colors.BOLD}running{Colors.RESET}"

                print(f"{Colors.BOLD}{name:12}{Colors.RESET} {status_str:30} {mem_str:20} {Colors.GRAY}PID: {info['pid']}{Colors.RESET}{instances}")
                print(f"             {Colors.GRAY}{desc}{Colors.RESET}")
                print()

            total_mcp_mem = sum(m['memory_mb'] for m in mcps.values())
            print(f"{Colors.GRAY}{'─' * 80}{Colors.RESET}")
            print(f"{Colors.BOLD}Total MCP Memory:{Colors.RESET} {format_memory(total_mcp_mem)}")
            print()

    print(f"{Colors.GRAY}{'─' * 80}{Colors.RESET}")
    print(f"\nCommands: {Colors.CYAN}devmon start <service>{Colors.RESET} | {Colors.CYAN}devmon stop <service>{Colors.RESET} | {Colors.CYAN}devmon logs <service>{Colors.RESET}\n")


def cmd_start(args):
    """Start a service"""
    if args.service == 'docker':
        print("Docker is managed by stack. Use: devmon pc group start <group>")
        return 2
    if args.service not in SERVICES:
        print(f"{Colors.RED}Error:{Colors.RESET} Unknown service '{args.service}'")
        print(f"Available services: {', '.join(SERVICES.keys())}")
        return 1

    service = SERVICES[args.service]['service']
    print(f"Starting {args.service}...")

    ret, out, err = run_cmd(['sudo', 'systemctl', 'start', service], capture=False)

    if ret == 0:
        print(f"{Colors.GREEN}✓{Colors.RESET} {args.service} started successfully")

        # Start monitor if exists
        if 'monitor' in SERVICES[args.service]:
            monitor = SERVICES[args.service]['monitor']
            run_cmd(['sudo', 'systemctl', 'start', monitor], capture=False)
            print(f"{Colors.GREEN}✓{Colors.RESET} Idle monitor started")
    else:
        print(f"{Colors.RED}✗{Colors.RESET} Failed to start {args.service}")
        return 1

    return 0


def cmd_stop(args):
    """Stop a service"""
    if args.service == 'docker':
        print("Docker is managed by stack. Use: devmon pc group stop <group>")
        return 2
    if args.service not in SERVICES:
        print(f"{Colors.RED}Error:{Colors.RESET} Unknown service '{args.service}'")
        print(f"Available services: {', '.join(SERVICES.keys())}")
        return 1

    service = SERVICES[args.service]['service']
    print(f"Stopping {args.service}...")

    ret, out, err = run_cmd(['sudo', 'systemctl', 'stop', service], capture=False)

    if ret == 0:
        print(f"{Colors.GREEN}✓{Colors.RESET} {args.service} stopped successfully")
    else:
        print(f"{Colors.RED}✗{Colors.RESET} Failed to stop {args.service}")
        return 1

    return 0


def cmd_restart(args):
    """Restart a service"""
    if args.service == 'docker':
        print("Docker is managed by stack. Use: devmon pc group start|stop <group>")
        return 2
    if args.service not in SERVICES:
        print(f"{Colors.RED}Error:{Colors.RESET} Unknown service '{args.service}'")
        print(f"Available services: {', '.join(SERVICES.keys())}")
        return 1

    service = SERVICES[args.service]['service']
    print(f"Restarting {args.service}...")

    ret, out, err = run_cmd(['sudo', 'systemctl', 'restart', service], capture=False)

    if ret == 0:
        print(f"{Colors.GREEN}✓{Colors.RESET} {args.service} restarted successfully")

        # Restart monitor if exists
        if 'monitor' in SERVICES[args.service]:
            monitor = SERVICES[args.service]['monitor']
            run_cmd(['sudo', 'systemctl', 'restart', monitor], capture=False)
            print(f"{Colors.GREEN}✓{Colors.RESET} Idle monitor restarted")
    else:
        print(f"{Colors.RED}✗{Colors.RESET} Failed to restart {args.service}")
        return 1

    return 0


def cmd_logs(args):
    """Show logs for a service"""
    if args.service not in SERVICES:
        print(f"{Colors.RED}Error:{Colors.RESET} Unknown service '{args.service}'")
        print(f"Available services: {', '.join(SERVICES.keys())}")
        return 1

    service = SERVICES[args.service]['service']

    cmd = ['journalctl', '-u', service, '--no-pager']

    if args.follow:
        cmd.append('-f')
    else:
        cmd.extend(['-n', str(args.lines)])

    # Run without capturing for interactive output
    subprocess.run(cmd)
    return 0


def cmd_pc(args):
    """Use the same typed local policy contract as Monkey Monitor GTK."""
    try:
        if args.pc_command in (None, 'status'):
            data = pc_status()
            if getattr(args, 'json', False):
                print(json.dumps(data, indent=2, ensure_ascii=False))
            else:
                quner = data.get('quner') if isinstance(data.get('quner'), dict) else {}
                calibration = quner.get('calibration')
                calibration = calibration if isinstance(calibration, dict) else {}
                policy_display = quner_policy_display(quner)
                selected = quner.get('selected_work_type')
                print(f"Work type: {selected if isinstance(selected, str) and selected else 'unavailable'}")
                print(policy_display.application)
                print(f"Quner: {policy_display.profile} · "
                      f"calibration {calibration.get('state') or 'unknown'}")
                if policy_display.thermal_override:
                    print(policy_display.thermal_override)
                for group in data.get('groups') or []:
                    if isinstance(group, dict):
                        keep = ' · keep running' if group.get('keep_live') else ''
                        cleanup = ' · idle cleanup on' if group.get('idle_managed') else ' · idle cleanup off'
                        print(f"{group.get('name') or group.get('id')}: "
                              f"{'running' if group.get('running') else 'stopped'}{keep}{cleanup} · "
                              f"{group.get('reason', '')}")
                lifecycle = data.get('lifecycle') or {}
                if isinstance(lifecycle, dict) and lifecycle.get('state') not in (None, 'idle'):
                    print(f"Last stack action: {lifecycle.get('group', 'unknown')} "
                          f"{lifecycle.get('action', 'action')} {lifecycle.get('state')} · "
                          f"{lifecycle.get('message', '')}")
                    result = lifecycle.get('result') or {}
                    if isinstance(result, dict):
                        if result.get('partial'):
                            print('Partial stop: some containers may still be running')
                        if any(isinstance(member, dict) and member.get('forced_or_sigkill')
                               for member in result.get('stopped', []) or []):
                            print('At least one container required forced termination')
            return 0
        if args.pc_command == 'worktype':
            if args.worktype_command in (None, 'list'):
                data = pc_status()
                quner = data.get('quner') or {}
                selected = quner.get('selected_work_type')
                for item in quner.get('work_types') or []:
                    if isinstance(item, dict):
                        marker = '*' if item.get('id') == selected else ' '
                        kind = 'measured' if item.get('calibrated') else 'default'
                        if item.get('configured') is False:
                            kind = 'unconfigured'
                        print(f"{marker} {item.get('id')}: {item.get('label')} ({kind})")
                return 0
            receipt = pc_request('set_work_type', work_type=args.work_type)
            if not isinstance(receipt, dict) or receipt.get('selected_work_type') != args.work_type:
                print('Quner returned no matching selection receipt; verify with devmon pc status.',
                      file=sys.stderr)
                return 2
            revision = receipt.get('revision')
            pending = receipt.get('selection_pending') is True
            print(f"Saved work type: {args.work_type}" +
                  (f" · revision {revision}" if revision is not None else '') +
                  (' · pending Quner application' if pending else ''))
            return 0
        if args.pc_command == 'calibrate':
            pc_request('calibrate_selected', desktop_background=True) if getattr(args, 'desktop', False) else pc_request('calibrate_selected')
            print('Calibration requested; use devmon pc status for live state.')
        elif args.pc_command == 'cancel':
            pc_request('cancel_calibration')
            print('Calibration cancellation requested.')
        elif args.pc_command == 'keep-live':
            pc_request('set_keep_live', group=args.group, keep_live=args.keep_live == 'on')
            print(f"Keep running {'enabled' if args.keep_live == 'on' else 'disabled'} for {args.group}.")
        elif args.pc_command == 'idle-cleanup':
            pc_request('set_idle_management', group=args.group,
                       enabled=args.idle_cleanup == 'on')
            print(f"Idle cleanup {'enabled' if args.idle_cleanup == 'on' else 'disabled'} "
                  f"for {args.group}; verify current policy with devmon pc status.")
        elif args.pc_command == 'stack-startup':
            pc_request('set_group_startup', group=args.group, mode=args.mode)
            print(f"{args.mode} startup requested for {args.group}; check live Docker readback with devmon pc status.")
        elif args.pc_command == 'group':
            pc_request('start_group' if args.group_command == 'start' else 'stop_group',
                       group=args.group)
            print(f"{args.group_command.capitalize()} requested for {args.group}.")
        return 0
    except ControlError as exc:
        print(f"PC controls: {exc}", file=sys.stderr)
        return 2


def main():
    parser = argparse.ArgumentParser(
        description='DevMon - Development Service Monitor',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  devmon status              Show status of all services
  devmon start mysql         Start MySQL
  devmon pc status           Show PC policy and container stacks
  devmon pc idle-cleanup GROUP on  Enable verified idle cleanup for a request-driven stack
  devmon pc keep-live GROUP on     Pin a stack that must keep running
  devmon restart mysql       Restart MySQL
  devmon logs mysql          Show MySQL logs
  devmon logs -f mysql       Follow MySQL logs
        """
    )

    subparsers = parser.add_subparsers(dest='command', help='Command to run')

    # status command
    subparsers.add_parser('status', help='Show status of all services')

    # start command
    start_parser = subparsers.add_parser('start', help='Start a service')
    start_parser.add_argument('service', help='Service name')

    # stop command
    stop_parser = subparsers.add_parser('stop', help='Stop a service')
    stop_parser.add_argument('service', help='Service name')

    # restart command
    restart_parser = subparsers.add_parser('restart', help='Restart a service')
    restart_parser.add_argument('service', help='Service name')

    # logs command
    logs_parser = subparsers.add_parser('logs', help='Show service logs')
    logs_parser.add_argument('service', help='Service name')
    logs_parser.add_argument('-f', '--follow', action='store_true', help='Follow log output')
    logs_parser.add_argument('-n', '--lines', type=int, default=50, help='Number of lines to show (default: 50)')

    pc_parser = subparsers.add_parser('pc', help='Quner work types and managed container stacks')
    pc_sub = pc_parser.add_subparsers(dest='pc_command')
    pc_status_parser = pc_sub.add_parser('status', help='Current policy and stack status')
    pc_status_parser.add_argument('--json', action='store_true', help='Print full machine-readable status')
    work_parser = pc_sub.add_parser('worktype', help='List or select work types')
    work_sub = work_parser.add_subparsers(dest='worktype_command')
    work_sub.add_parser('list', help='List available work types')
    work_set = work_sub.add_parser('set', help='Persist a work type')
    work_set.add_argument('work_type')
    calibrate_parser = pc_sub.add_parser('calibrate', help='Calibrate the selected work type')
    calibrate_parser.add_argument('--desktop', action='store_true', help='Measure CPU work with bounded desktop background and stability checks')
    pc_sub.add_parser('cancel', help='Cancel an active calibration')
    keep_parser = pc_sub.add_parser('keep-live', help='Pin or unpin a managed stack')
    keep_parser.add_argument('group')
    keep_parser.add_argument('keep_live', choices=('on', 'off'))
    idle_parser = pc_sub.add_parser('idle-cleanup',
                                    help='Opt a request-driven stack into ten-minute idle cleanup')
    idle_parser.add_argument('group')
    idle_parser.add_argument('idle_cleanup', choices=('on', 'off'))
    stack_startup = pc_sub.add_parser('stack-startup', help='Choose Docker boot policy for running stack members')
    stack_startup.add_argument('group')
    stack_startup.add_argument('mode', choices=('Manual', 'Automatic'))
    group_parser = pc_sub.add_parser('group', help='Start or stop a managed stack')
    group_sub = group_parser.add_subparsers(dest='group_command', required=True)
    for action in ('start', 'stop'):
        action_parser = group_sub.add_parser(action)
        action_parser.add_argument('group')

    args = parser.parse_args()

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

    # Route to appropriate command handler
    commands = {
        'status': cmd_status,
        'start': cmd_start,
        'stop': cmd_stop,
        'restart': cmd_restart,
        'logs': cmd_logs,
        'pc': cmd_pc,
    }

    return commands[args.command](args)


if __name__ == '__main__':
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        print(f"\n{Colors.YELLOW}Interrupted{Colors.RESET}")
        sys.exit(130)
