#!/usr/bin/env python3
"""
Production HTTP Server for QuickBooks POS Help Documentation
Optimized for high traffic (100,000+ users)
"""
import http.server
import socketserver
import os
import logging
from datetime import datetime, timedelta

PORT = 8888
DIRECTORY = "QB_Help_Web"

# Configure minimal logging
logging.basicConfig(level=logging.ERROR)

class OptimizedHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    # Disable verbose request logging
    def log_message(self, format, *args):
        # Only log errors, not every request
        if args[1][0] in ('4', '5'):  # 4xx and 5xx errors only
            super().log_message(format, *args)
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)
    
    def end_headers(self):
        # Disable caching to ensure changes take effect immediately
        self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
        self.send_header('Pragma', 'no-cache')
        self.send_header('Expires', '0')
        
        super().end_headers()

os.chdir(os.path.dirname(os.path.abspath(__file__)))

# Use ThreadingTCPServer for handling multiple simultaneous connections
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    allow_reuse_address = True
    daemon_threads = True
    request_queue_size = 50  # Increase queue size for high traffic

print(f"="*60)
print(f"QuickBooks POS Help Documentation Server")
print(f"="*60)
print(f"Server running at:")
print(f"  Local:    http://localhost:{PORT}/POS_Help.html")
print(f"  Network:  http://192.168.10.130:{PORT}/POS_Help.html")
print(f"\nOptimizations:")
print(f"  ✓ Static asset caching (1 year)")
print(f"  ✓ Minimal logging (errors only)")
print(f"  ✓ Multi-threaded connections")
print(f"  ✓ High traffic queue (50 requests)")
print(f"\nFor 100,000+ users, consider:")
print(f"  - Installing nginx (sudo apt install nginx)")
print(f"  - Using a CDN for static assets")
print(f"  - Load balancing across multiple servers")
print(f"\nPress Ctrl+C to stop the server")
print(f"="*60)

try:
    with ThreadedTCPServer(("0.0.0.0", PORT), OptimizedHTTPRequestHandler) as httpd:
        httpd.serve_forever()
except KeyboardInterrupt:
    print("\n\nServer stopped.")
