import http.server
import socketserver
import json
import os
import subprocess
import signal
import time
import sys
from urllib.parse import urlparse

# --- PORTABLE DEPENDENCY LOADING ---
BACKEND_DIR = os.path.dirname(os.path.abspath(__file__))
LIBS_DIR = os.path.join(BACKEND_DIR, 'libs')
if os.path.exists(LIBS_DIR):
    sys.path.insert(0, LIBS_DIR)
# -----------------------------------

# Use environment variables if available (good for cloud hosting)
CONTROL_PORT = int(os.environ.get('CONTROL_PORT', 5001))
GALLERY_PORT = int(os.environ.get('GALLERY_PORT', 5000))
BACKEND_DIR = os.path.dirname(os.path.abspath(__file__))
# Prefer server.py as it's the most portable (dependency-free)
GALLERY_SERVER_SCRIPT = os.path.join(BACKEND_DIR, 'server.py')

class ControlHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        super().end_headers()

    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

    def do_GET(self):
        parsed_path = urlparse(self.path)
        
        if parsed_path.path == '/status':
            is_running = self.is_gallery_running()
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({"running": is_running}).encode())
            
        elif parsed_path.path == '/start':
            if not self.is_gallery_running():
                try:
                    # Robust start across platforms
                    # On Windows, we use creationflags to hide the window
                    CREATE_NO_WINDOW = 0x08000000 if os.name == 'nt' else 0
                    
                    # Use the same python executable that's running this script
                    subprocess.Popen([sys.executable, GALLERY_SERVER_SCRIPT], 
                                   creationflags=CREATE_NO_WINDOW,
                                   cwd=BACKEND_DIR)
                    
                    time.sleep(2) # Give it a bit more time to bind to the port
                    self.send_response(200)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    self.wfile.write(json.dumps({"status": "started"}).encode())
                except Exception as e:
                    self.send_error(500, str(e))
            else:
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"status": "already_running"}).encode())
                
        elif parsed_path.path == '/stop':
            try:
                # Find and kill the process running on GALLERY_PORT
                if os.name == 'nt': # Windows
                    # Using taskkill by finding the PID associated with the port
                    cmd = f'for /f "tokens=5" %a in (\'netstat -aon ^| findstr :{GALLERY_PORT}\') do taskkill /F /PID %a'
                    subprocess.run(cmd, shell=True, capture_output=True)
                else: # Linux/Mac
                    # Using fuser or lsof to kill the process on the port
                    cmd = f'fuser -k {GALLERY_PORT}/tcp'
                    subprocess.run(cmd, shell=True, capture_output=True)
                
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"status": "stopped"}).encode())
            except Exception as e:
                self.send_error(500, str(e))
        else:
            self.send_error(404)

    def is_gallery_running(self):
        import socket
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.settimeout(1)
                return s.connect_ex(('localhost', GALLERY_PORT)) == 0
        except:
            return False

class ThreadingTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    allow_reuse_address = True

if __name__ == '__main__':
    print("\n==========================================")
    print("    UDEC Professional Control Server")
    print("==========================================")
    print(f"API Endpoint: http://localhost:{CONTROL_PORT}")
    print(f"Target:       {GALLERY_SERVER_SCRIPT}")
    print("------------------------------------------")
    
    # Auto-start gallery server on launch
    def check_and_start():
        import socket
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.settimeout(1)
                if s.connect_ex(('localhost', GALLERY_PORT)) != 0:
                    print("[*] Gallery server not detected. Starting automatically...")
                    CREATE_NO_WINDOW = 0x08000000 if os.name == 'nt' else 0
                    subprocess.Popen([sys.executable, GALLERY_SERVER_SCRIPT], 
                                   creationflags=CREATE_NO_WINDOW,
                                   cwd=BACKEND_DIR)
                    print("[SUCCESS] Gallery server launched.")
                else:
                    print("[OK] Gallery server already running.")
        except Exception as e:
            print(f"[!] Error auto-starting gallery: {e}")

    check_and_start()
    
    print("------------------------------------------")
    print("Keep this window open for the admin panel.")
    print("------------------------------------------\n")
    try:
        with ThreadingTCPServer(("", CONTROL_PORT), ControlHandler) as httpd:
            httpd.serve_forever()
    except KeyboardInterrupt:
        print("\nStopping control server...")
        sys.exit(0)
    except Exception as e:
        print(f"\nFATAL ERROR: {str(e)}")
        sys.exit(1)
