import json
import time
import random
import os
import hashlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

LOG_FILE = "server_log.json"

class MockVideoAPI(BaseHTTPRequestHandler):
    def log_request(self, format, *args):
        # Suppress standard logging to stdout to keep grading output clean
        pass
        
    def do_POST(self):
        if self.path == '/generate':
            content_length = int(self.headers.get('Content-Length', 0))
            post_data = self.rfile.read(content_length)
            
            # Simulate processing time required for concurrency checks
            time.sleep(0.3)
            
            try:
                req = json.loads(post_data.decode('utf-8'))
                prompt_text = req.get("prompt", "")
                
                # 30% chance to fail with 429 or 503 to test Tenacity retry logic
                if random.random() < 0.3:
                    error_code = random.choice([429, 503])
                    
                    # Log the failed attempt
                    self.record_log(prompt_text, "failed", error_code)
                    
                    self.send_response(error_code)
                    self.end_headers()
                    self.wfile.write(json.dumps({"error": f"Simulated {error_code} error"}).encode('utf-8'))
                    return
                
                # FIX: Use a stable cryptographic digest instead of Python's randomized hash()
                video_id = hashlib.sha256(prompt_text.encode('utf-8')).hexdigest()[:8]
                
                response_data = {
                    "status": "success",
                    "video_url": f"https://mock-video-api.local/renders/shot_{video_id}.mp4",
                    "applied_glitch": req.get("glitch_factor", 0.0),
                    "applied_motion": req.get("motion", 0.0)
                }
                
                # Log successful attempt
                self.record_log(prompt_text, "success", 200)
                
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps(response_data).encode('utf-8'))
            except Exception as e:
                self.send_response(400)
                self.end_headers()
                self.wfile.write(json.dumps({"error": str(e)}).encode('utf-8'))
                
    def record_log(self, prompt, status, code):
        log_entry = {
            "timestamp": time.time(),
            "prompt": prompt[:30], # Just enough to identify
            "status": status,
            "code": code
        }
        # Append to log file safely
        try:
            with open(LOG_FILE, "a") as f:
                f.write(json.dumps(log_entry) + "\n")
        except:
            pass

if __name__ == "__main__":
    # Clear old log file
    if os.path.exists(LOG_FILE):
        os.remove(LOG_FILE)
        
    # Seed the RNG if grading to prevent spurious timeout failures from unlucky streaks
    seed_val = os.environ.get("MOCK_API_SEED")
    if seed_val:
        random.seed(int(seed_val))
        
    server = ThreadingHTTPServer(('127.0.0.1', 8000), MockVideoAPI)
    print("Mock Video API running on port 8000 (with simulated flakiness)...")
    server.serve_forever()
