"""
License guard — obfuscate this file in production builds.

Only this file + app/services/license_validator.py + app/config/pricing.py
+ app/services/license_limits.py + app/config/build_config.py
need to be Cython-compiled. Everything else can remain as readable bytecode.
"""

import sys

import click


def check_license(skip: bool) -> dict:
    """Validate license. Returns a result dict; exits on hard failure."""
    if skip:
        from app.config.build_config import BUILD_TYPE
        if BUILD_TYPE != "development":
            click.echo(
                "ERROR: --skip-license / RIVET_SKIP_LICENSE is only available "
                "in development builds.",
                err=True,
            )
            sys.exit(2)
        return {"valid": True, "license_type": "development", "features": {}}

    try:
        from app.services.license_validator import LicenseValidator, LicenseValidationError
        result = LicenseValidator.validate()
    except LicenseValidationError as exc:
        click.echo(f"ERROR: {exc}", err=True)
        click.echo(
            "To get a license: download the Cerebion Rivet desktop app at cerebion.com/download\n"
            "  (includes a free trial) or purchase at cerebion.com/pricing.\n"
            "  Once you have a key, set: RIVET_LICENSE_KEY=<your-key>",
            err=True,
        )
        sys.exit(2)
    except Exception as exc:
        click.echo(
            f"WARNING: License check failed ({exc}). Proceeding in offline mode.",
            err=True,
        )
        return {"valid": True, "license_type": "unknown", "features": {}}

    is_valid = result.get("valid") or result.get("is_trial_active")
    if not is_valid:
        click.echo(
            f"ERROR: {result.get('message', 'License not valid.')}",
            err=True,
        )
        click.echo(
            "To get a license: download the Cerebion Rivet desktop app at cerebion.com/download\n"
            "  (includes a free trial) or purchase at cerebion.com/pricing.\n"
            "  Once you have a key, set: RIVET_LICENSE_KEY=<your-key>",
            err=True,
        )
        sys.exit(2)

    tier = result.get("license_type", "unknown")
    click.echo(f"License: {tier}", err=True)
    return result


def require_feature(license_result: dict, feature: str, flag: str) -> None:
    """Exit with an error if the license does not include a feature."""
    enabled = bool(license_result.get("features", {}).get(feature, False))
    if not enabled:
        tier = license_result.get("license_type", "unknown")
        click.echo(
            f"ERROR: {flag} requires an Enterprise license (current tier: {tier}).",
            err=True,
        )
        sys.exit(2)
