from http.server import SimpleHTTPRequestHandler, HTTPServer
import json
from urllib.parse import quote

class CORSRequestHandler(SimpleHTTPRequestHandler):
    def end_headers(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', '*')
        super().end_headers()

    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

    def do_POST(self):
        if self.path == '/set_path':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            data = json.loads(post_data.decode('utf-8'))
            path = data['path']
            # Normalize backslashes to slashes
            path = path.replace('\\', '/')
            # Quote the path for URL safety
            quoted_path = quote(path)
            # Generate rules.json
            rules = [
                {
                    "id": 1,
                    "priority": 1,
                    "action": {
                        "type": "redirect",
                        "redirect": {
                            "regexSubstitution": "file:///" + quoted_path
                        }
                    },
                    "condition": {
                        "regexFilter": "^https?://(www\\.)?example\\.com/.*",
                        "resourceTypes": ["main_frame"]
                    }
                }
            ]
            with open('rules.json', 'w') as f:
                json.dump(rules, f)
            self.send_response(200)
            self.end_headers()
            self.wfile.write(b'OK')
        else:
            self.send_response(404)
            self.end_headers()

if __name__ == "__main__":
    server = HTTPServer(('localhost', 8002), CORSRequestHandler)
    print("Serving rules.json with CORS enabled on http://localhost:8002")
    server.serve_forever()
