"""
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."""

    def __init__(self, status):
        self.status = status
        super().__init__(status.get("message", "License check failed."))


def enforce_license_periodic(grace_seconds=3600):
    """Runtime license check. Returns license payload if valid, raises on failure."""
    lic = load_license(auto_trial=False)
    if not lic:
        raise LicenseViolation({
            "status": "LICENSE_INVALIDATED",
            "message": "License is no longer valid.",
        })
    if lic.get("error"):
        from .validator import get_license_status
        raise LicenseViolation(get_license_status())
    return lic.get("payload", {})


    """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.
    Auto-trial is attempted before failing.
    """
    # First attempt: load existing license
    lic = load_license(auto_trial=False)

    # No license — try auto-trial before giving up
    if not lic:
        from src.license.validator import _auto_trial, _LAST_AUTO_TRIAL_ERROR
        trial_result = _auto_trial()
        if trial_result:
            return trial_result
        # Auto-trial failed — show helpful message
        trial_error = _LAST_AUTO_TRIAL_ERROR
        raise LicenseViolation({
            "status": "UNLICENSED",
            "message": (
                "Gold AutoTrade 需要激活才能使用。\n\n"
                "首次启动将自动申请14天免费试用。\n"
                f"试用申请结果: {trial_error.get('message', '服务器不可达') if trial_error else '未知错误'}\n\n"
                "请检查网络连接后重启系统。\n"
                "如果已有激活密钥，请运行:\n"
                "  GoldAutoTradeEngine.exe --activate GAT-XXXX-XXXX-XXXX-XXXX"
            ),
        })

    if lic.get("error"):
        # ── Trial HW mismatch: auto-reclaim to rebind ──
        if lic.get("error") == "HARDWARE_MISMATCH":
            from src.license.validator import _auto_trial
            trial_result = _auto_trial()
            if trial_result:
                return trial_result
        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
