#!/usr/bin/env python3
"""
Terminal Remote Control Server
Allows iOS app to remotely open Terminal windows on Mac
Port: 6000
"""

from flask import Flask, request, jsonify
from flask_cors import CORS
import subprocess
import os
import logging
from logging.handlers import RotatingFileHandler
from datetime import datetime
import sys

app = Flask(__name__)
CORS(app)  # Allow requests from iOS app

# Setup advanced logging
LOG_DIR = os.path.expanduser('~/Library/Logs')
os.makedirs(LOG_DIR, exist_ok=True)

# Main log file with rotation
main_log_path = os.path.join(LOG_DIR, 'terminal-remote-server.log')
main_handler = RotatingFileHandler(
    main_log_path,
    maxBytes=5*1024*1024,  # 5MB
    backupCount=5
)
main_handler.setLevel(logging.DEBUG)
main_formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
main_handler.setFormatter(main_formatter)

# Error log file
error_log_path = os.path.join(LOG_DIR, 'terminal-remote-errors.log')
error_handler = RotatingFileHandler(
    error_log_path,
    maxBytes=5*1024*1024,  # 5MB
    backupCount=5
)
error_handler.setLevel(logging.ERROR)
error_handler.setFormatter(main_formatter)

# Console handler
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(main_formatter)

# Configure root logger
logging.basicConfig(
    level=logging.DEBUG,
    handlers=[main_handler, error_handler, console_handler]
)

logger = logging.getLogger(__name__)
logger.info("=" * 60)
logger.info("Terminal Remote Server Starting")
logger.info(f"Main log: {main_log_path}")
logger.info(f"Error log: {error_log_path}")
logger.info("=" * 60)

# Request logging middleware
@app.before_request
def log_request():
    logger.debug(f"→ {request.method} {request.path} from {request.remote_addr}")
    if request.method == 'POST' and request.is_json:
        logger.debug(f"  Body: {request.get_json()}")

@app.after_request
def log_response(response):
    logger.debug(f"← {response.status_code} {request.path}")
    return response

@app.route('/health', methods=['GET'])
def health_check():
    """Health check endpoint"""
    return jsonify({
        'status': 'ok',
        'service': 'Terminal Remote Control',
        'version': '1.0.0'
    })

@app.route('/open-terminal', methods=['POST'])
def open_terminal():
    """Open a new Terminal window"""
    try:
        # Use AppleScript to open new Terminal window
        command = ['osascript', '-e', 'tell application "Terminal" to do script ""']
        result = subprocess.run(command, capture_output=True, text=True, timeout=5)

        if result.returncode == 0:
            return jsonify({
                'success': True,
                'message': 'Terminal window opened successfully',
                'output': result.stdout.strip()
            })
        else:
            return jsonify({
                'success': False,
                'message': 'Failed to open Terminal',
                'error': result.stderr
            }), 500

    except subprocess.TimeoutExpired:
        return jsonify({
            'success': False,
            'message': 'Command timeout'
        }), 500
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@app.route('/execute-command', methods=['POST'])
def execute_command():
    """Execute a command in a new Terminal window"""
    try:
        data = request.get_json()
        command = data.get('command', '')

        if not command:
            return jsonify({
                'success': False,
                'message': 'No command provided'
            }), 400

        # Escape command for AppleScript
        escaped_command = command.replace('\\', '\\\\').replace('"', '\\"')

        # Open Terminal and execute command
        applescript = f'tell application "Terminal" to do script "{escaped_command}"'
        result = subprocess.run(['osascript', '-e', applescript],
                              capture_output=True, text=True, timeout=5)

        if result.returncode == 0:
            return jsonify({
                'success': True,
                'message': f'Command executed: {command}',
                'output': result.stdout.strip()
            })
        else:
            return jsonify({
                'success': False,
                'message': 'Failed to execute command',
                'error': result.stderr
            }), 500

    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@app.route('/activate-terminal', methods=['POST'])
def activate_terminal():
    """Bring Terminal to front"""
    try:
        command = ['osascript', '-e', 'tell application "Terminal" to activate']
        result = subprocess.run(command, capture_output=True, text=True, timeout=5)

        if result.returncode == 0:
            return jsonify({
                'success': True,
                'message': 'Terminal activated'
            })
        else:
            return jsonify({
                'success': False,
                'message': 'Failed to activate Terminal',
                'error': result.stderr
            }), 500

    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@app.route('/open-claude', methods=['POST'])
def open_claude():
    """Open Claude Code in a new Terminal window"""
    try:
        # Open Terminal and run claude directly
        # User will see the trust prompt and can manually accept
        # After first trust, Claude won't ask again
        command = '/Users/neog/auto-claude-v2.sh'
        escaped_command = command.replace('\\', '\\\\').replace('"', '\\"')

        applescript = f'tell application "Terminal" to do script "{escaped_command}"'
        result = subprocess.run(['osascript', '-e', applescript],
                              capture_output=True, text=True, timeout=5)

        if result.returncode == 0:
            return jsonify({
                'success': True,
                'message': 'Claude Code opened successfully',
                'output': result.stdout.strip()
            })
        else:
            return jsonify({
                'success': False,
                'message': 'Failed to open Claude Code',
                'error': result.stderr
            }), 500

    except subprocess.TimeoutExpired:
        return jsonify({
            'success': False,
            'message': 'Command timeout'
        }), 500
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@app.route('/debug/logs', methods=['GET'])
def debug_logs():
    """Get last 100 lines of server log for debugging"""
    try:
        lines_count = int(request.args.get('lines', 100))
        with open(main_log_path, 'r') as f:
            lines = f.readlines()
            last_lines = lines[-lines_count:]
            return jsonify({
                'success': True,
                'log_file': main_log_path,
                'total_lines': len(lines),
                'returned_lines': len(last_lines),
                'logs': ''.join(last_lines)
            })
    except FileNotFoundError:
        return jsonify({
            'success': False,
            'message': 'Log file not found yet'
        }), 404
    except Exception as e:
        logger.error(f"Error reading logs: {e}")
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@app.route('/debug/stats', methods=['GET'])
def debug_stats():
    """Get server statistics for debugging"""
    try:
        import psutil
        import time

        process = psutil.Process()
        uptime = time.time() - process.create_time()

        return jsonify({
            'success': True,
            'server': {
                'uptime_seconds': round(uptime, 2),
                'uptime_formatted': f"{int(uptime // 3600)}h {int((uptime % 3600) // 60)}m",
                'cpu_percent': process.cpu_percent(interval=0.1),
                'memory_mb': round(process.memory_info().rss / 1024 / 1024, 2),
                'threads': process.num_threads()
            },
            'logs': {
                'main_log': main_log_path,
                'error_log': error_log_path
            }
        })
    except ImportError:
        # psutil not installed, return basic info
        return jsonify({
            'success': True,
            'server': {
                'status': 'running',
                'psutil': 'not installed'
            },
            'logs': {
                'main_log': main_log_path,
                'error_log': error_log_path
            }
        })
    except Exception as e:
        logger.error(f"Error getting stats: {e}")
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

if __name__ == '__main__':
    print("🖥️  Terminal Remote Control Server")
    print("=" * 50)
    print(f"Port: 6000")
    print(f"Local: http://localhost:6000")
    print(f"Tailscale: http://100.75.88.8:6000")
    print("=" * 50)
    print("\nEndpoints:")
    print("  GET  /health            - Health check")
    print("  POST /open-terminal     - Open new Terminal window")
    print("  POST /execute-command   - Execute command in Terminal")
    print("  POST /activate-terminal - Bring Terminal to front")
    print("  POST /open-claude       - Open Claude Code in new Terminal")
    print("  GET  /debug/logs        - Get server logs (debug)")
    print("  GET  /debug/stats       - Get server statistics (debug)")
    print(f"\n📁 Logs:")
    print(f"  Main: {main_log_path}")
    print(f"  Errors: {error_log_path}")
    print("\n🟢 Server starting...\n")

    app.run(host='0.0.0.0', port=6000, debug=True)
