#!/usr/bin/env python3
from http.server import HTTPServer, BaseHTTPRequestHandler
import json, os

DATA_FILE = '/var/www/boutique/boutique_data.json'
PASSWORD  = 'boutique2024'
PORT      = 8081

class Handler(BaseHTTPRequestHandler):
    def cors(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, X-Password')
    def auth(self):
        return self.headers.get('X-Password') == PASSWORD
    def do_OPTIONS(self):
        self.send_response(200); self.cors(); self.end_headers()
    def do_GET(self):
        if self.path == '/api/load':
            if not self.auth():
                self.send_response(401); self.end_headers(); return
            data = {}
            if os.path.exists(DATA_FILE):
                with open(DATA_FILE, 'r') as f:
                    data = json.load(f)
            body = json.dumps(data).encode()
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.cors(); self.end_headers(); self.wfile.write(body)
        elif self.path == '/health':
            self.send_response(200); self.cors(); self.end_headers()
            self.wfile.write(b'ok')
        else:
            self.send_response(404); self.end_headers()
    def do_POST(self):
        length = int(self.headers.get('Content-Length', 0))
        body = self.rfile.read(length)
        if self.path == '/api/save':
            if not self.auth():
                self.send_response(401); self.end_headers(); return
            data = json.loads(body)
            with open(DATA_FILE, 'w') as f:
                json.dump(data, f, indent=2)
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.cors(); self.end_headers()
            self.wfile.write(b'{"status":"ok"}')
        else:
            self.send_response(404); self.end_headers()
    def log_message(self, *a): pass

if __name__ == '__main__':
    print('Boutique sync running on port ' + str(PORT))
    HTTPServer(('0.0.0.0', PORT), Handler).serve_forever()
