#!/usr/bin/env python3
"""
Sharey - Command Line Utility
Cross-platform management script for Sharey application
"""

import sys
import os
import subprocess
import argparse
from pathlib import Path
import json
import time

class ShareyManager:
    def __init__(self):
        self.script_dir = Path(__file__).parent
        os.chdir(self.script_dir)
        
    def print_banner(self):
        """Print Sharey banner"""
        print("🚀 Sharey - Command Line Utility")
        print("=" * 40)

    def start_app(self, dev_mode=False, production_mode=False):
        """Start the application"""
        if production_mode:
            print("🏭 Starting Sharey in production mode with Gunicorn...")
            return subprocess.run([sys.executable, "production.py"])
        elif dev_mode:
            print("🔧 Starting Sharey in development mode...")
            if Path("dev.py").exists():
                return subprocess.run([sys.executable, "dev.py"])
            else:
                os.environ['FLASK_ENV'] = 'development'
                return subprocess.run([sys.executable, "run.py"])
        else:
            print("🚀 Starting Sharey with full checks...")
            return subprocess.run([sys.executable, "run.py"])

    def setup_environment(self):
        """Set up development environment"""
        print("📦 Setting up development environment...")
        
        if Path("dev-setup.sh").exists():
            return subprocess.run(["./dev-setup.sh"])
        else:
            # Fallback Python setup
            print("Running Python setup...")
            
            # Create venv if it doesn't exist
            if not Path(".venv").exists():
                print("Creating virtual environment...")
                subprocess.run([sys.executable, "-m", "venv", ".venv"])
            
            # Install dependencies
            if Path("requirements.txt").exists():
                print("Installing dependencies...")
                pip_path = ".venv/bin/pip"
                subprocess.run([pip_path, "install", "-r", "requirements.txt"])
            
            # Copy config if needed
            if not Path("config.json").exists() and Path("config.json.example").exists():
                print("Creating config.json from example...")
                import shutil
                shutil.copy2("config.json.example", "config.json")
                print("✏️ Please edit config.json with your settings!")

    def clean_project(self):
        """Clean up temporary files"""
        print("🧹 Cleaning project...")
        
        if Path("scripts/clean.sh").exists():
            subprocess.run(["./scripts/clean.sh"])
        else:
            # Python cleanup
            print("Removing Python cache...")
            self._remove_pycache()
            
            print("Removing temporary files...")
            temp_patterns = ["*.tmp", "*.temp", "debug_*.html", "test_*.ppm"]
            for pattern in temp_patterns:
                for file in Path(".").glob(pattern):
                    file.unlink(missing_ok=True)
            
            print("Cleaning old logs...")
            logs_dir = Path("logs")
            if logs_dir.exists():
                for log_file in logs_dir.glob("*.log"):
                    # Remove logs older than 7 days
                    if time.time() - log_file.stat().st_mtime > 7 * 24 * 3600:
                        log_file.unlink(missing_ok=True)
            
            print("Removing backup files...")
            for backup in Path(".").glob("*.backup"):
                backup.unlink(missing_ok=True)
            for backup in Path(".").glob("*.bak"):
                backup.unlink(missing_ok=True)

    def _remove_pycache(self):
        """Remove Python cache directories"""
        for pycache in Path(".").rglob("__pycache__"):
            if pycache.is_dir():
                import shutil
                shutil.rmtree(pycache, ignore_errors=True)
        
        for pyc in Path(".").rglob("*.pyc"):
            pyc.unlink(missing_ok=True)

    def run_tests(self):
        """Run tests"""
        print("🧪 Running tests...")
        
        tests_dir = Path("tests")
        if tests_dir.exists():
            os.chdir(tests_dir)
            result = subprocess.run([sys.executable, "-m", "pytest", "-v"])
            os.chdir(self.script_dir)
            return result
        else:
            print("❌ No tests directory found")
            return subprocess.CompletedProcess([], 1)

    def show_status(self):
        """Show system status"""
        print("📊 Sharey System Status")
        print("=" * 30)
        print(f"📁 Working directory: {os.getcwd()}")
        print(f"🐍 Python version: {sys.version.split()[0]}")
        
        # Virtual environment check
        venv_path = Path(".venv")
        if venv_path.exists():
            print("📦 Virtual environment: ✅ Present")
        else:
            print("📦 Virtual environment: ❌ Missing")
        
        # Configuration check
        config_path = Path("config.json")
        if config_path.exists():
            print("⚙️  Configuration: ✅ Present")
            try:
                with open(config_path, 'r') as f:
                    config_data = json.load(f)
                    print(f"   Host: {config_data.get('host', 'Not set')}")
                    print(f"   Port: {config_data.get('port', 'Not set')}")
                    print(f"   Debug: {config_data.get('debug', 'Not set')}")
            except json.JSONDecodeError:
                print("   ⚠️  Invalid JSON format")
        else:
            print("⚙️  Configuration: ❌ Missing")
        
        # Dependencies check
        requirements_path = Path("requirements.txt")
        if requirements_path.exists():
            print("📋 Dependencies file: ✅ Present")
        else:
            print("📋 Dependencies file: ❌ Missing")
        
        # Project structure
        print("\n📂 Project structure:")
        structure_dirs = ["src", "tests", "scripts", "docs", "logs"]
        for dir_name in structure_dirs:
            dir_path = Path(dir_name)
            if dir_path.exists():
                print(f"   {dir_name}/: ✅")
            else:
                print(f"   {dir_name}/: ❌")

    def show_logs(self):
        """Show recent logs"""
        print("📜 Recent Sharey logs:")
        
        logs_dir = Path("logs")
        if logs_dir.exists():
            log_files = list(logs_dir.glob("*.log"))
            if log_files:
                for log_file in sorted(log_files, key=lambda x: x.stat().st_mtime, reverse=True)[:3]:
                    print(f"\n--- {log_file.name} (last 10 lines) ---")
                    try:
                        with open(log_file, 'r') as f:
                            lines = f.readlines()
                            for line in lines[-10:]:
                                print(line.rstrip())
                    except Exception as e:
                        print(f"Error reading {log_file}: {e}")
            else:
                print("No log files found")
        else:
            print("❌ No logs directory found")

    def install_service(self):
        """Install Sharey as a system service (Linux)"""
        print("🔧 Installing Sharey as a system service...")
        
        service_content = f"""[Unit]
Description=Sharey File Sharing Platform
After=network.target

[Service]
Type=simple
User={os.getenv('USER')}
WorkingDirectory={os.getcwd()}
Environment=PATH={os.getcwd()}/.venv/bin
ExecStart={os.getcwd()}/.venv/bin/python {os.getcwd()}/run.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
"""
        
        service_file = Path("/tmp/sharey.service")
        with open(service_file, 'w') as f:
            f.write(service_content)
        
        print("Service file created. To install, run:")
        print(f"sudo cp {service_file} /etc/systemd/system/")
        print("sudo systemctl daemon-reload")
        print("sudo systemctl enable sharey")
        print("sudo systemctl start sharey")

def main():
    parser = argparse.ArgumentParser(
        description="Sharey - Command Line Utility",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Commands:
  start      Start the application (full checks)
  dev        Start in development mode (quick)
  production Start in production mode with Gunicorn
  setup      Set up development environment
  clean      Clean up temporary files
  test       Run tests
  status     Show system status
  logs       Show recent logs
  service    Install as system service (Linux)

Examples:
  python sharey.py start
  python sharey.py dev
  python sharey.py production
  python sharey.py status
        """
    )
    
    parser.add_argument('command', 
                       choices=['start', 'dev', 'production', 'setup', 'clean', 'test', 'status', 'logs', 'service'],
                       help='Command to execute')
    
    if len(sys.argv) == 1:
        parser.print_help()
        return
    
    args = parser.parse_args()
    manager = ShareyManager()
    
    # Execute command
    try:
        if args.command == 'start':
            manager.print_banner()
            result = manager.start_app(dev_mode=False)
        elif args.command == 'dev':
            manager.print_banner()
            result = manager.start_app(dev_mode=True)
        elif args.command == 'production':
            manager.print_banner()
            result = manager.start_app(production_mode=True)
        elif args.command == 'setup':
            manager.print_banner()
            manager.setup_environment()
            result = subprocess.CompletedProcess([], 0)
        elif args.command == 'clean':
            manager.print_banner()
            manager.clean_project()
            result = subprocess.CompletedProcess([], 0)
        elif args.command == 'test':
            manager.print_banner()
            result = manager.run_tests()
        elif args.command == 'status':
            manager.print_banner()
            manager.show_status()
            result = subprocess.CompletedProcess([], 0)
        elif args.command == 'logs':
            manager.print_banner()
            manager.show_logs()
            result = subprocess.CompletedProcess([], 0)
        elif args.command == 'service':
            manager.print_banner()
            manager.install_service()
            result = subprocess.CompletedProcess([], 0)
        
        sys.exit(result.returncode if hasattr(result, 'returncode') else 0)
        
    except KeyboardInterrupt:
        print("\n👋 Interrupted by user")
        sys.exit(0)
    except Exception as e:
        print(f"❌ Error: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()
