# AUTO-GENERATED FILE - DO NOT EDIT
# This file was automatically generated by the XDK build tool.
# Any manual changes will be overwritten on the next generation.
#!/usr/bin/env python3
"""
AUTO-GENERATED FILE - DO NOT EDIT
This file was automatically generated by the XDK build tool.
Any manual changes will be overwritten on the next generation.

Watch for changes and regenerate documentation automatically.
"""

import os
import sys
import time
import subprocess
from pathlib import Path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

print("🚀 Starting X API SDK Documentation Watch Server...")


class DocsHandler(FileSystemEventHandler):
    """Handle file system events for documentation regeneration."""


    def __init__(self):
        self.last_regeneration = 0
        self.debounce_seconds = 2


    def on_modified(self, event):
        if event.is_directory:
            return
        # Only watch Python files
        if not event.src_path.endswith(".py"):
            return
        # Skip if in docs or build directories
        if "docs" in event.src_path or "__pycache__" in event.src_path:
            return
        # Debounce rapid changes
        current_time = time.time()
        if current_time - self.last_regeneration < self.debounce_seconds:
            return
        self.last_regeneration = current_time
        print(f"📝 File changed: {event.src_path}")
        regenerate_docs()


def regenerate_docs():
    """Regenerate documentation."""
    print("🔄 Regenerating documentation...")
    try:
        result = subprocess.run(
            [sys.executable, "scripts/generate-docs-simple.py"],
            check=True,
            capture_output=True,
            text=True,
        )
        print(result.stdout)
        print("✅ Documentation regenerated successfully")
    except subprocess.CalledProcessError as e:
        print(f"❌ Failed to regenerate documentation: {e}")
        print(f"stderr: {e.stderr}")


def start_server():
    """Start a simple HTTP server for docs."""
    try:
        import http.server
        import socketserver
        import threading
        PORT = 8080
        Handler = http.server.SimpleHTTPRequestHandler
        def run_server():
            with socketserver.TCPServer(("", PORT), Handler) as httpd:
                print(f"📚 Starting documentation server on http://localhost:{PORT}")
                httpd.serve_forever()
        server_thread = threading.Thread(target=run_server, daemon=True)
        server_thread.start()
        return server_thread
    except Exception as e:
        print(f"⚠️  Could not start HTTP server: {e}")
        return None


        def run_server():
            with socketserver.TCPServer(("", PORT), Handler) as httpd:
                print(f"📚 Starting documentation server on http://localhost:{PORT}")
                httpd.serve_forever()

        server_thread = threading.Thread(target=run_server, daemon=True)
        server_thread.start()
        return server_thread
    except Exception as e:
        print(f"⚠️  Could not start HTTP server: {e}")
        return None


# Initial documentation generation
regenerate_docs()
server_thread = start_server()

# Watch for changes
event_handler = DocsHandler()
observer = Observer()

# Watch xdk directory
xdk_path = Path("xdk")
if xdk_path.exists():
    observer.schedule(event_handler, str(xdk_path), recursive=True)
    observer.start()
    print("👀 Watching for changes... Press Ctrl+C to stop")

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n🛑 Shutting down documentation server...")
        observer.stop()

    observer.join()
else:
    print("⚠️  xdk directory not found")
