#!/usr/bin/env python3
"""
CGI Script pour partage cross-device sur hébergement Infomaniak
"""

import cgi
import cgitb
import json
import os
import sys
import uuid
from pathlib import Path

# Activer le mode debug (à désactiver en production)
cgitb.enable()

# Configuration
PREVIEW_DIR = Path(__file__).parent.parent / "shared_previews"
PREVIEW_DIR.mkdir(exist_ok=True)

def get_base_url():
    """Construire l'URL de base"""
    protocol = "https" if os.environ.get("HTTPS") == "on" else "http"
    host = os.environ.get("HTTP_HOST", "localhost")
    return f"{protocol}://{host}"

def handle_share():
    """Gérer la création de prévisualisation"""
    # Lire les données POST
    content_length = int(os.environ.get("CONTENT_LENGTH", 0))
    post_data = sys.stdin.read(content_length)

    try:
        data = json.loads(post_data)
        html_content = data.get("html", "")

        if not html_content:
            raise ValueError("Contenu HTML manquant")

        # Générer un ID unique
        preview_id = str(uuid.uuid4())
        preview_path = PREVIEW_DIR / preview_id
        preview_path.mkdir(parents=True, exist_ok=True)

        # Sauvegarder le fichier HTML
        html_file = preview_path / "index.html"
        html_file.write_text(html_content, encoding="utf-8")

        # Construire l'URL de partage
        base_url = get_base_url()
        script_name = os.environ.get("SCRIPT_NAME", "")
        builder_path = "/".join(script_name.split("/")[:-2])  # Remonter de /cgi-bin/share.py
        share_url = f"{base_url}{builder_path}/shared_previews/{preview_id}/"

        # Réponse JSON
        response = {
            "success": True,
            "previewId": preview_id,
            "shareUrl": share_url
        }

        print("Content-Type: application/json")
        print("Access-Control-Allow-Origin: *")
        print()
        print(json.dumps(response))

    except Exception as e:
        print("Content-Type: application/json")
        print("Status: 400 Bad Request")
        print()
        print(json.dumps({"error": str(e)}))

def handle_options():
    """Gérer les requêtes preflight CORS"""
    print("Content-Type: text/plain")
    print("Access-Control-Allow-Origin: *")
    print("Access-Control-Allow-Methods: GET, POST, OPTIONS")
    print("Access-Control-Allow-Headers: Content-Type")
    print()

# Main
if __name__ == "__main__":
    request_method = os.environ.get("REQUEST_METHOD", "")

    if request_method == "POST":
        handle_share()
    elif request_method == "OPTIONS":
        handle_options()
    else:
        print("Content-Type: text/plain")
        print("Status: 405 Method Not Allowed")
        print()
        print("Method not allowed")
