#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Git Pusher - License Endpoints
Endpoints REST pour gérer les licences
"""

import sys
import os
import json
import tempfile
from http.server import BaseHTTPRequestHandler

# Ajouter le chemin du module
sys.path.insert(0, os.path.join(os.path.dirname(__file__)))

from license_validator import LicenseValidator, get_license_status, LICENSE_FILE_PATH

class LicenseHandler(BaseHTTPRequestHandler):
    """Handler pour les requêtes de licence"""
    
    def do_OPTIONS(self):
        """Gérer les requêtes OPTIONS (CORS preflight)"""
        self.send_response(200)
        self.send_headers()
        self.end_headers()
    
    def do_GET(self):
        """Gérer les requêtes GET"""
        if self.path == '/custom/git_pusher/license_status':
            self.handle_license_status()
        else:
            self.send_error(404)
    
    def do_POST(self):
        """Gérer les requêtes POST"""
        if self.path == '/custom/git_pusher/install_license':
            self.handle_install_license()
        elif self.path == '/custom/git_pusher/request_trial':
            self.handle_request_trial()
        else:
            self.send_error(404)
    
    def send_headers(self):
        """Envoyer les headers CORS"""
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
    
    def handle_license_status(self):
        """Vérifier le statut de la licence"""
        try:
            status = get_license_status()
            
            self.send_response(200)
            self.send_headers()
            self.end_headers()
            
            self.wfile.write(json.dumps(status).encode())
        
        except Exception as e:
            self.send_response(500)
            self.send_headers()
            self.end_headers()
            
            self.wfile.write(json.dumps({
                'licensed': False,
                'errors': [f'Erreur serveur: {str(e)}']
            }).encode())
    
    def handle_install_license(self):
        """Installer un fichier de licence uploadé"""
        try:
            # Lire le body
            content_length = int(self.headers['Content-Length'])
            body = self.rfile.read(content_length)
            data = json.loads(body.decode())
            
            license_content = data.get('license_file')
            filename = data.get('filename', 'uploaded.lic')
            
            if not license_content:
                raise Exception("Aucun contenu de licence fourni")
            
            # Créer un fichier temporaire
            with tempfile.NamedTemporaryFile(mode='w', suffix='.lic', delete=False) as temp_file:
                temp_file.write(license_content)
                temp_path = temp_file.name
            
            try:
                # Valider et installer
                validator = LicenseValidator()
                result = validator.install_license(temp_path, LICENSE_FILE_PATH)
                
                self.send_response(200)
                self.send_headers()
                self.end_headers()
                
                self.wfile.write(json.dumps(result).encode())
            
            finally:
                # Nettoyer le fichier temporaire
                if os.path.exists(temp_path):
                    os.remove(temp_path)
        
        except Exception as e:
            self.send_response(400)
            self.send_headers()
            self.end_headers()
            
            self.wfile.write(json.dumps({
                'success': False,
                'message': f'Erreur: {str(e)}'
            }).encode())
    
    def handle_request_trial(self):
        """Créer une licence d'essai"""
        try:
            from datetime import datetime, timedelta
            import socket
            import hashlib
            
            # Générer une licence d'essai basique (7 jours)
            hostname = socket.gethostname()
            trial_license = {
                "license": {
                    "version": "1.0",
                    "license_id": "TRIAL-" + hashlib.md5(
                        f"{hostname}{datetime.now()}".encode()
                    ).hexdigest()[:8].upper(),
                    "customer": {
                        "name": "Trial User",
                        "hostname": hostname
                    },
                    "validity": {
                        "issued": datetime.now().isoformat(),
                        "expires": (datetime.now() + timedelta(days=7)).isoformat(),
                        "days": 7
                    },
                    "limits": {
                        "max_pushes": 50,
                        "max_apps": None
                    },
                    "features": {
                        "git_push": True,
                        "multi_branch": False,
                        "auto_commit": False,
                        "webhooks": False
                    },
                    "type": "trial"
                },
                "signature": "TRIAL-NO-SIGNATURE",
                "checksum": "TRIAL"
            }
            
            # Créer le dossier si nécessaire
            os.makedirs(os.path.dirname(LICENSE_FILE_PATH), exist_ok=True)
            
            # Sauvegarder
            with open(LICENSE_FILE_PATH, 'w') as f:
                json.dump(trial_license, f, indent=2)
            
            self.send_response(200)
            self.send_headers()
            self.end_headers()
            
            self.wfile.write(json.dumps({
                'success': True,
                'message': 'Licence d\'essai créée (7 jours, 50 pushes max)',
                'license_info': {
                    'license_id': trial_license['license']['license_id'],
                    'type': 'trial',
                    'expires': trial_license['license']['validity']['expires'],
                    'days_remaining': 7
                }
            }).encode())
        
        except Exception as e:
            self.send_response(500)
            self.send_headers()
            self.end_headers()
            
            self.wfile.write(json.dumps({
                'success': False,
                'message': f'Erreur: {str(e)}'
            }).encode())
    
    def log_message(self, format, *args):
        """Override pour éviter les logs HTTP par défaut"""
        pass
