#!/usr/bin/env python3
"""
Klaviyo Proxy Server
Serves static files and proxies Klaviyo API requests to handle CORS
"""

import http.server
import socketserver
import urllib.request
import urllib.parse
import json
import os
import posixpath
from pathlib import Path


class KlaviyoProxyHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        # Set the directory to serve files from the workspace root
        super().__init__(*args, directory="/Users/neoclaw/.openclaw/workspace", **kwargs)
    
    def end_headers(self):
        # Add CORS headers to all responses
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization, revision')
        super().end_headers()
    
    def do_OPTIONS(self):
        # Handle preflight requests
        self.send_response(200)
        self.end_headers()
    
    def do_GET(self):
        # Check if this is a Klaviyo API proxy request
        if self.path.startswith('/api/klaviyo/'):
            self.handle_klaviyo_proxy()
        else:
            # Serve static files
            super().do_GET()
    
    def handle_klaviyo_proxy(self):
        try:
            # Parse the request path and query parameters
            parsed_url = urllib.parse.urlparse(self.path)
            query_params = urllib.parse.parse_qs(parsed_url.query)
            
            # Extract API key from query params
            if 'key' not in query_params:
                self.send_error(400, "Missing API key parameter")
                return
            
            api_key = query_params['key'][0]
            
            # Build the Klaviyo API URL
            # Remove /api/klaviyo prefix and add the Klaviyo base URL
            klaviyo_path = parsed_url.path[12:]  # Remove '/api/klaviyo' from path only
            
            # Remove the key parameter and rebuild query string for Klaviyo
            filtered_params = {k: v for k, v in query_params.items() if k != 'key'}
            query_string = urllib.parse.urlencode(filtered_params, doseq=True)
            
            klaviyo_url = f"https://a.klaviyo.com/api{klaviyo_path}"
            if query_string:
                klaviyo_url += f"?{query_string}"
            
            print(f"Proxying request to: {klaviyo_url}")
            
            # Create the request to Klaviyo
            request = urllib.request.Request(klaviyo_url)
            request.add_header('Authorization', f'Klaviyo-API-Key {api_key}')
            request.add_header('revision', '2024-02-15')
            request.add_header('Accept', 'application/json')
            
            # Make the request to Klaviyo
            with urllib.request.urlopen(request) as response:
                data = response.read()
                content_type = response.getheader('Content-Type', 'application/json')
                
                # Send response back to browser
                self.send_response(200)
                self.send_header('Content-Type', content_type)
                self.send_header('Content-Length', str(len(data)))
                self.end_headers()
                self.wfile.write(data)
                
        except urllib.error.HTTPError as e:
            print(f"Klaviyo API error: {e.code} {e.reason}")
            self.send_response(e.code)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            error_response = json.dumps({
                'error': f'Klaviyo API error: {e.code} {e.reason}'
            }).encode()
            self.wfile.write(error_response)
            
        except Exception as e:
            print(f"Proxy error: {str(e)}")
            self.send_error(500, f"Proxy error: {str(e)}")


def main():
    PORT = 9899
    
    print(f"Starting Klaviyo proxy server on port {PORT}...")
    print(f"Serving files from: /Users/neoclaw/.openclaw/workspace")
    print(f"API proxy endpoint: /api/klaviyo/")
    
    class ReusableTCPServer(socketserver.TCPServer):
        allow_reuse_address = True
    
    with ReusableTCPServer(("", PORT), KlaviyoProxyHandler) as httpd:
        print(f"Server running at http://localhost:{PORT}")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nShutting down server...")


if __name__ == "__main__":
    main()