from __future__ import annotations

"""Générateur de licences enveloppant la logique de bas niveau."""

import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Dict, Optional

from .generators.license_generator import LicenceData, build_licence, write_licence_file


class LicenseGenerator:
    """Générateur à usage interne pour produire des fichiers .lic signés."""

    def __init__(self, private_key_path: Path) -> None:
        self.private_key_path = private_key_path

    def generate(self, config: Dict, output_path: Optional[Path] = None) -> LicenceData:
        licence = build_licence(config, self.private_key_path)
        if output_path is not None:
            write_licence_file(licence, output_path)
        return licence

    @staticmethod
    def default_config(
        licence_id: str,
        tier: str,
        valid_until: datetime,
        max_users: int,
        max_domains: int,
        features: Dict[str, bool],
        super_admin_email: str,
        grace_hours: int = 168,
        db_seed: Optional[str] = None,
    ) -> Dict:
        """Construire un dictionnaire de configuration conforme au chargeur runtime."""

        if db_seed is None:
            from secrets import token_hex

            db_seed = token_hex(32)

        feature_list = [name for name, enabled in features.items() if enabled]

        subscription = {
            "tier": tier.upper(),
            "maxUsers": max_users,
            "maxDomains": max_domains,
            "validUntil": valid_until.replace(tzinfo=timezone.utc).isoformat(),
            "features": feature_list,
        }

        config = {
            "licenseId": licence_id,
            "superAdmin": {"email": super_admin_email},
            "subscription": subscription,
            "encryption": {
                "dbKeySeed": db_seed,
                "algorithm": "AES-256-GCM",
                "keyDerivation": "PBKDF2-SHA256",
            },
            "antiTampering": {},
            "validation": {
                "gracePeriodHours": grace_hours,
            },
        }

        return config


def licence_to_json(licence: LicenceData) -> str:
    """Convertir la licence signée en JSON pretty-printed."""

    return json.dumps(licence.payload, indent=2)
