import http.server
import socketserver
import requests
from urllib.parse import urlparse, urlunparse
import logging

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)

PROXY_PORT = 8080
HEADER_TO_MODIFY = "Content-Type"
NEW_HEADER_VALUE = "application/dash+xml"

class ProxyHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        url_parsed = urlparse(self.path[1:])

        try:
            response = requests.get(urlunparse(url_parsed))

            modified_headers = dict(response.headers)
            modified_headers[HEADER_TO_MODIFY] = NEW_HEADER_VALUE

            self.send_response(response.status_code)
            for header, value in modified_headers.items():
                self.send_header(header, value)
            self.end_headers()

            self.wfile.write(response.content)
        except requests.RequestException as e:
            self.send_error(502, f"Error al contactar el servidor de destino: {e}")

with socketserver.TCPServer(("", PROXY_PORT), ProxyHandler) as httpd:
    logging.info(f"Proxy corriendo en el puerto {PROXY_PORT}")
    httpd.serve_forever()