"""
Rivet License Startup Check

Add this to app.py startup event to validate license on server startup.
"""

import logging
from app.services.license_validator import LicenseValidator, LicenseValidationError

logger = logging.getLogger(__name__)


def validate_license_on_startup():
    """
    Validate Rivet license on server startup.

    This function:
    1. Validates license against license server
    2. Falls back to cached validation if offline
    3. Logs license status and warnings
    4. Starts background license polling for online licenses
    5. Does NOT block startup (allows degraded operation)
    """
    try:
        logger.info("=== Rivet License Validation ===")

        validation = LicenseValidator.validate()

        # Log license details
        logger.info(f"[OK] License Type: {validation['license_type']}")
        logger.info(f"[OK] Expires: {validation.get('expires_at', 'Never')}")
        logger.info(f"[OK] Seats Remaining: {validation.get('seats_remaining', 'Unlimited')}")

        # Log enabled features
        enabled_features = [k for k, v in validation.get('features', {}).items() if v]
        logger.info(f"[OK] Features: {', '.join(enabled_features)}")

        # Check if operating in offline mode
        if validation.get("offline_mode"):
            days = validation.get("days_since_last_check", 0)

            if days == 0:
                logger.info("  Using cached validation (development/trial mode)")
            elif days >= 6:
                logger.warning(f"  WARNING: OFFLINE MODE: License check required soon!")
                logger.warning(f"  WARNING: Last online check: {days} days ago (max 7 days)")
                logger.warning(f"  WARNING: Please connect to internet for license verification")
            elif days >= 3:
                logger.warning(f"  WARNING: OFFLINE MODE: {days} days since last online check")
                logger.warning(f"  WARNING: Please connect to internet soon for license verification")
            else:
                logger.info(f"  Using cached validation ({days} days old)")
        else:
            logger.info("  Online validation successful")

        logger.info("=== License Valid ===\n")
        
        # Start background license polling for online licenses
        LicenseValidator.start_license_polling()

    except LicenseValidationError as e:
        logger.error("=" * 60)
        logger.error("LICENSE VALIDATION FAILED")
        logger.error(f"   Error: {e}")
        logger.error("=" * 60)
        logger.error("Rivet will start in LIMITED MODE (basic features only)")
        logger.error("Please check:")
        logger.error("  1. RIVET_LICENSE_KEY is set correctly in .env")
        logger.error("  2. LICENSE_API_KEY is set correctly in .env")
        logger.error("  3. License server is running (LICENSE_SERVER_URL)")
        logger.error("  4. Internet connection is available")
        logger.error("=" * 60 + "\n")

        # Don't raise - allow Rivet to start with limited features
        # If you want to block startup on license failure, uncomment:
        # raise SystemExit(1)
