#!/usr/bin/env python3
"""Server for property scorecards — serves forms + captures submissions."""
import json, os, http.server, urllib.parse
from pathlib import Path
from datetime import datetime

PORT = 8787
DIR = Path(__file__).parent
TEXAS_FEEDBACK = DIR / "texas-feedback.json"
CANYON_FEEDBACK = DIR / "canyon-lake-feedback.json"

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=str(DIR), **kwargs)
    
    def do_POST(self):
        if self.path in ("/submit", "/submit-canyon"):
            length = int(self.headers.get("Content-Length", 0))
            body = self.rfile.read(length).decode("utf-8")
            data = json.loads(body)
            data["received_at"] = datetime.now().isoformat()
            
            feedback_file = CANYON_FEEDBACK if self.path == "/submit-canyon" else TEXAS_FEEDBACK
            
            existing = []
            if feedback_file.exists():
                existing = json.loads(feedback_file.read_text())
            existing.append(data)
            feedback_file.write_text(json.dumps(existing, indent=2))
            
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.end_headers()
            self.wfile.write(json.dumps({"status": "ok"}).encode())
            print(f"✅ Feedback received on {self.path} from {data.get('reviewer', 'unknown')}")
        else:
            self.send_error(404)
    
    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        self.end_headers()

print(f"🏡 Scorecard server running at http://localhost:{PORT}")
print(f"   Texas:       http://localhost:{PORT}/texas-scorecard.html")
print(f"   Canyon Lake: http://localhost:{PORT}/canyon-lake-scorecard.html")
http.server.HTTPServer(("0.0.0.0", PORT), Handler).serve_forever()
