"""
Tiny HTTP server that triggers `mkdocs build --clean` on POST /build.
Runs inside the MkDocs container alongside `mkdocs serve`.
Listens on port 8001 (internal only, not exposed to host).
"""

import subprocess
import json
import time
from http.server import HTTPServer, BaseHTTPRequestHandler


class BuildHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path != '/build':
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'{"error":"not found"}')
            return

        start = time.time()
        try:
            result = subprocess.run(
                ['mkdocs', 'build', '--clean'],
                cwd='/docs',
                capture_output=True,
                text=True,
                timeout=120,
            )
            duration = int((time.time() - start) * 1000)
            body = json.dumps({
                'success': result.returncode == 0,
                'output': (result.stdout + result.stderr) or '(no output)',
                'duration': duration,
            })
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(body.encode())
        except subprocess.TimeoutExpired:
            duration = int((time.time() - start) * 1000)
            body = json.dumps({
                'success': False,
                'output': 'Build timed out after 120s',
                'duration': duration,
            })
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(body.encode())
        except Exception as e:
            duration = int((time.time() - start) * 1000)
            body = json.dumps({
                'success': False,
                'output': f'Build error: {str(e)}',
                'duration': duration,
            })
            self.send_response(500)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(body.encode())

    def do_GET(self):
        if self.path == '/health':
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(b'{"status":"ok"}')
            return
        self.send_response(404)
        self.end_headers()

    def log_message(self, format, *args):
        # Suppress default logging to keep container logs clean
        pass


if __name__ == '__main__':
    server = HTTPServer(('0.0.0.0', 8001), BuildHandler)
    print('Build trigger server listening on :8001')
    server.serve_forever()
