from flask import Flask, request, jsonify
from flask_cors import CORS
import time
import json
import base64
import os
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.serialization import load_pem_private_key

app = Flask(__name__)
CORS(app)

# Load private key from file (create this file in step 2)
with open('private_key.pem', 'rb') as f:
    PRIVATE_KEY = f.read()

# License store (simple dictionary - replace with database later)
LICENSES = {
    # Demo license key - replace with your actual license generation
    "PRO-DEMO-1234-ABCD": {
        "type": "ENTERPRISE",
        "org_name": "Poseidon Ltd",
        "seats": 10,
        "expires_at": int(time.time() + 365 * 24 * 3600)  # 1 year
    }
}

def sign_data(data):
    """Sign the license data for verification"""
    private_key = load_pem_private_key(PRIVATE_KEY, password=None)
    signature = private_key.sign(
        json.dumps(data, sort_keys=True).encode('utf-8'),
        padding.PKCS1v15(),
        hashes.SHA256()
    )
    return base64.b64encode(signature).decode('utf-8')

@app.route('/license/validate', methods=['POST'])
def validate_license():
    """Validate a license key"""
    data = request.json
    license_key = data.get('licenseKey')
    org_id = data.get('organizationId', 'poseidon')
    user_id = data.get('userId', 'system')
    
    print(f"Validating: {license_key} for {org_id}")
    
    # Check if license exists
    license_info = LICENSES.get(license_key)
    if not license_info:
        return jsonify({
            "valid": False,
            "message": "Invalid license key"
        })
    
    # Check if expired
    if license_info["expires_at"] < time.time():
        return jsonify({
            "valid": False,
            "message": "License has expired"
        })
    
    # Build license data
    license_data = {
        "licenseKey": license_key,
        "licenseType": license_info["type"],
        "organizationId": org_id,
        "organizationName": license_info["org_name"],
        "userId": user_id,
        "seatsTotal": license_info["seats"],
        "seatsUsed": 1,
        "issuedAt": int((time.time() - 30 * 24 * 3600) * 1000),
        "expiresAt": license_info["expires_at"] * 1000,
        "features": [
            "batch_processing",
            "gpu_acceleration",
            "rest_api",
            "translation",
            "cloud_sync",
            "team_collaboration",
            "audit_logging"
        ],
        "featureFlags": {
            "batch_processing": True,
            "gpu_acceleration": True,
            "rest_api": True,
            "translation": True,
            "cloud_sync": True
        }
    }
    
    # Sign the data
    signature = sign_data(license_data)
    
    return jsonify({
        "valid": True,
        "signature": signature,
        "license": license_data
    })

@app.route('/license/activate', methods=['POST'])
def activate_license():
    """Activate a license with activation code"""
    data = request.json
    license_key = data.get('licenseKey')
    
    print(f"Activating: {license_key}")
    
    # In production, verify activation code here
    return jsonify({
        "success": True,
        "message": "License activated successfully",
        "license": LICENSES.get(license_key)
    })

@app.route('/license/deactivate', methods=['POST'])
def deactivate_license():
    """Deactivate a license"""
    print("Deactivating license")
    return jsonify({"success": True})

@app.route('/license/heartbeat', methods=['POST'])
def heartbeat():
    """Check if license is still valid"""
    data = request.json
    license_key = data.get('licenseKey')
    
    valid = license_key in LICENSES
    return jsonify({
        "valid": valid,
        "license": LICENSES.get(license_key) if valid else None
    })

@app.route('/health', methods=['GET'])
def health():
    """Health check endpoint"""
    return jsonify({"status": "ok", "timestamp": time.time()})

if __name__ == '__main__':
    # Listen on all interfaces so the hosting can route requests
    app.run(host='0.0.0.0', port=5000, debug=False)