import os
import requests
from flask import Flask, request, Response

app = Flask(__name__)

# Hugging Face Space Configuration
HF_SPACE_URL = "https://fiazul-photocard-bot.hf.space" 
HF_TOKEN = os.environ.get("HF_TOKEN")
PROXY_SECRET = "DailyEventProxy2026!"

@app.route('/photocard/fb_proxy.php', methods=['POST'])
def proxy_fb():
    """
    Acts as the Facebook proxy, replacing the PHP file.
    This bypasses HF Spaces egress blocks because this executes on cPanel!
    """
    if request.headers.get("X-Proxy-Secret") != PROXY_SECRET:
        return {"error": "Forbidden: Invalid proxy secret"}, 403
        
    path = request.args.get("path")
    if not path:
        return {"error": "Missing path parameter"}, 400
        
    url = f"https://graph.facebook.com/{path}"
    
    # Forward form data and files exactly as-is to Facebook
    files = {k: (v.filename, v.stream, v.mimetype) for k, v in request.files.items()}
    res = requests.post(url, data=request.form, files=files, timeout=90)
    
    return Response(res.content, res.status_code, content_type=res.headers.get('Content-Type'))

@app.route('/', defaults={'path': ''}, methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
@app.route('/<path:path>', methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
def proxy_hf(path):
    """
    Reflects all other traffic securely to the Private Hugging Face Space.
    """
    url = f"{HF_SPACE_URL}/{path}"
    
    # We must aggressively strip ALL cPanel proxy headers (X-Forwarded, X-Real-IP, etc.)
    # Otherwise Hugging Face thinks we are requesting the wrong server and throws a 404.
    safe_headers = ['user-agent', 'accept', 'accept-language', 'accept-encoding', 'cookie', 'content-type', 'content-length', 'origin', 'x-app-authorization']
    headers = {}
    for key, value in request.headers:
        if key.lower() in safe_headers:
            headers[key] = value
    
    # Attach our secure HF Token to authorize against the Private space
    if HF_TOKEN:
        headers['Authorization'] = f"Bearer {HF_TOKEN}"
        
    # Preserve query strings (e.g. /api/status?v=1)
    if request.query_string:
        url = f"{url}?{request.query_string.decode('utf-8')}"
        
    res = requests.request(
        method=request.method,
        url=url,
        headers=headers,
        data=request.get_data(),
        allow_redirects=False
    )
    
    # Filter out chunked encoding headers as Flask will automatically re-chunk
    excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
    resp_headers = [(name, value) for (name, value) in res.raw.headers.items()
               if name.lower() not in excluded_headers]
               
    return Response(res.content, res.status_code, resp_headers)

# cPanel Passenger requires 'application' globally exported
application = app
