import json
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
import payment as apple

# Load the certificate and private key
certificate_pem = open('ApplePay.crt.pem', 'rb').read()
private_key_pem = open('ApplePay.key.pem', 'rb').read()

# Initialize the Apple Pay payment object
payment = apple.Payment(certificate_pem, private_key_pem)

class PaymentRequestHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        # Only allow the /process-payment path
        if self.path != "/process-payment":
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'{"error": "Endpoint not found"}')
            return

        try:
            # Read and decode the request body
            content_length = int(self.headers['Content-Length'])
            body = self.rfile.read(content_length)
            payment_json = json.loads(body)

            # Validate the required fields
            ephemeral_public_key = payment_json.get('header', {}).get('ephemeralPublicKey')
            encrypted_data = payment_json.get('data')

            if not ephemeral_public_key or not encrypted_data:
                self.send_response(400)
                self.end_headers()
                self.wfile.write(b'{"success": False, "error": "Invalid payment data"}')
                return

            # Decrypt the payment data
            decrypted_bytes = payment.decrypt(ephemeral_public_key, encrypted_data)
            
            # Decode bytes to string (assuming the decrypted content is JSON)
            decrypted_json = json.loads(decrypted_bytes.decode('utf-8'))

            # Send a success response with the decrypted data
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            response = {
                "success": True,
                "data": decrypted_json
            }
            self.wfile.write(json.dumps(response).encode('utf-8'))

        except json.JSONDecodeError:
            self.send_response(400)
            self.end_headers()
            self.wfile.write(b'{"success": False, "error": "Invalid JSON format"}')

        except Exception as e:
            self.send_response(500)
            self.end_headers()
            error_response = {"success": False, "error": str(e)}
            self.wfile.write(json.dumps(error_response).encode('utf-8'))

def run(server_class=HTTPServer, handler_class=PaymentRequestHandler):
    # Parse the port number from CLI arguments
    port = 8080  # Default port
    if len(sys.argv) > 1:
        try:
            port = int(sys.argv[1])
        except ValueError:
            print("Invalid port number. Falling back to default port 8080.")

    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f"Starting server on port {port}...")
    httpd.serve_forever()

if __name__ == "__main__":
    run()
