"""
License startup guard — blocks execution if no valid license is present.
Must be called at the top of pipeline.py and gui_backend.py entry points.
"""
from __future__ import annotations

import sys
from pathlib import Path
from typing import Any

from .validator import load_license, get_license_status


class LicenseViolation(Exception):
    """Raised when license check fails — caught by top-level entry points."""
    def __init__(self, status: dict[str, Any]):
        self.status = status
        super().__init__(status.get("message", "License check failed."))


def enforce_license() -> dict[str, Any]:
    """
    Verify license at startup. Returns status dict on success.
    Raises LicenseViolation on failure.

    Called at the top of pipeline.py and gui_backend.py.
    """
    lic = load_license()

    if not lic:
        raise LicenseViolation({
            "status": "UNLICENSED",
            "message": (
                "No valid license found.\n\n"
                "Gold AutoTrade requires a license to run.\n"
                "Contact us to purchase a license:\n"
                "  WeChat/QQ: goldautotrade\n"
                "  Email:     support@goldauto.top\n"
                "  Website:   https://goldauto.top/license\n\n"
                "Already have a key? Activate it:\n"
                "  python3 -m src.license.activate --key GAT-XXXX-XXXX-XXXX-XXXX"
            ),
        })

    if lic.get("error"):
        raise LicenseViolation(get_license_status())

    return lic


def enforce_license_or_warn() -> dict[str, Any]:
    """
    Verify license but only warn on failure (non-blocking).
    Used in development/training modes.
    """
    lic = load_license()
    if not lic or lic.get("error"):
        status = get_license_status()
        print(f"[LICENSE] WARNING: {status['message']}", file=sys.stderr)
        return status
    return lic
