import frappe
import requests
from urllib.parse import urlparse
from custom_ui.db_utils import build_success_response, build_error_response
import logging

allowed_hosts = ["api.zippopotam.us", "nominatim.openstreetmap.org"] # Update this list with trusted domains as needed

@frappe.whitelist(allow_guest=True)
def request(url, method="GET", data=None, headers=None):
    """
    Generic proxy for external API requests.
    WARNING: Only allow requests to trusted domains.
    """
    parsed_url = urlparse(url)
    if parsed_url.hostname not in allowed_hosts:
        frappe.throw(f"Requests to {parsed_url.hostname} are not allowed.", frappe.PermissionError)
    try:
        resp = requests.request(
            method=method.upper(),
            url=url,
            json=frappe.parse_json(data) if data else None,
            headers=frappe.parse_json(headers) if headers else None,
            timeout=10
        )
        resp.raise_for_status()
        try:
            return build_success_response(resp.json())
        except ValueError:
            return build_success_response({"text": resp.text})
    except requests.exceptions.RequestException as e:
        frappe.log_error(message=str(e), title="Proxy Request Failed")
        frappe.throw("Failed to fetch data from external API.")