#!/usr/bin/env python3
"""Development server for western-cv-template.html with live reload.

Usage:
    python3 profile/resume-server.py [--port PORT] [--host HOST]

Opens the resume at http://<HOST>:<PORT>/western-cv-template.html
Auto-reloads the browser when the file changes (polls every 1.5s).
"""

import os
import sys
import signal
import argparse
from http.server import HTTPServer, SimpleHTTPRequestHandler
from urllib.parse import urlparse

DIR = os.path.dirname(os.path.abspath(__file__))
HTML = "western-cv-template.html"
HTML_PATH = os.path.join(DIR, HTML)

LIVE_RELOAD_SCRIPT = """
<script>
(function(){var t=null;setInterval(function(){fetch('/_mtime').then(function(r){return r.text();}).then(function(n){if(t&&t!==n)location.reload();t=n;});},1500);})();
</script>
"""

class ResumeHandler(SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIR, **kwargs)

    def do_GET(self):
        path = urlparse(self.path).path
        if path == '/_mtime':
            self.send_response(200)
            self.send_header('Content-Type', 'text/plain')
            self.send_header('Cache-Control', 'no-cache, no-store')
            self.end_headers()
            self.wfile.write(str(os.path.getmtime(HTML_PATH)).encode())
            return
        if path.rstrip('/') == '/' + HTML:
            self.send_response(200)
            self.send_header('Content-Type', 'text/html; charset=utf-8')
            self.send_header('Cache-Control', 'no-cache, no-store')
            self.end_headers()
            with open(HTML_PATH, 'rb') as f:
                content = f.read()
            content = content.replace(b'</body>', LIVE_RELOAD_SCRIPT.encode() + b'</body>')
            self.wfile.write(content)
            return
        super().do_GET()

    def log_message(self, format, *args):
        sys.stderr.write(f"[resume-server] {args[0]} {args[1]} {args[2]}\n")


def main():
    parser = argparse.ArgumentParser(description="Resume dev server with live reload")
    parser.add_argument('--port', type=int, default=8080, help='Port (default: 8080)')
    parser.add_argument('--host', default='0.0.0.0', help='Host (default: 0.0.0.0)')
    args = parser.parse_args()

    server = HTTPServer((args.host, args.port), ResumeHandler)

    def cleanup(sig, frame):
        print("\n[resume-server] stopping...")
        server.shutdown()
        sys.exit(0)

    signal.signal(signal.SIGINT, cleanup)
    signal.signal(signal.SIGTERM, cleanup)

    url = f"http://localhost:{args.port}/{HTML}"
    # for 0.0.0.0 show a useful LAN hint, but resolve actual hostname
    import socket
    hostname = socket.gethostname()
    lan_url = f"http://{hostname}:{args.port}/{HTML}"

    print(f"  ┌─ resume-server ──────────────────────")
    print(f"  │  Local:  {url}")
    print(f"  │  LAN:    {lan_url}")
    print(f"  │  (Ctrl+C to stop)")
    print(f"  └────────────────────────────────────────")
    print(f"  Watches: {HTML_PATH}")

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()


if __name__ == '__main__':
    main()