#!/usr/bin/env python3
"""
Novyx Core - Security Configuration Check
==========================================
Validates security configuration at startup to prevent accidental
production deployments with development defaults.

Usage:
    from tools.security import check_security_config
    check_security_config()  # Call at API startup
"""

import os
import sys
from typing import List


def check_security_config() -> List[str]:
    """
    Check for insecure default configuration values.

    Behavior:
        - Development (NOVYX_ENVIRONMENT=development): Print warnings only
        - Non-development: Print warnings to stderr
        - If NOVYX_STRICT_SECURITY=1: Exit with code 1 on any warning

    Returns:
        List of warning messages (empty if config is secure)
    """
    warnings = []

    # Check API key
    api_key = os.getenv("NOVYX_API_KEY", "")
    if _is_default_secret(api_key):
        warnings.append(
            "NOVYX_API_KEY is using default value or is too short. "
            "Set a secure API key for production."
        )

    # Check JWT secret
    jwt_secret = os.getenv("NOVYX_JWT_SECRET", "")
    if _is_default_secret(jwt_secret, min_length=32):
        warnings.append(
            "NOVYX_JWT_SECRET is using default value or is shorter than 32 characters. "
            "Set a secure secret for production."
        )

    # Determine environment and behavior
    environment = os.getenv("NOVYX_ENVIRONMENT", "").lower()
    is_development = environment == "development"
    strict_mode = os.getenv("NOVYX_STRICT_SECURITY", "0") == "1"

    # Output warnings
    if warnings:
        if is_development:
            # Development: gentle warning to stdout
            for w in warnings:
                print(f"[DEV WARNING] {w}")
        else:
            # Non-development: loud warning to stderr
            print("\n" + "=" * 60, file=sys.stderr)
            print("SECURITY WARNING - Insecure Configuration Detected", file=sys.stderr)
            print("=" * 60, file=sys.stderr)
            for w in warnings:
                print(f"  - {w}", file=sys.stderr)
            print("=" * 60 + "\n", file=sys.stderr)

            # Strict mode: exit
            if strict_mode:
                print(
                    "Exiting due to NOVYX_STRICT_SECURITY=1. "
                    "Fix configuration or set NOVYX_ENVIRONMENT=development.",
                    file=sys.stderr
                )
                sys.exit(1)

    return warnings


def _is_default_secret(value: str, min_length: int = 16) -> bool:
    """
    Check if a secret value is a known default or too short.

    Args:
        value: The secret value to check
        min_length: Minimum acceptable length (default: 16)

    Returns:
        True if the value appears to be a default or insecure
    """
    if not value:
        return True

    if len(value) < min_length:
        return True

    # Known default marker
    if "change-in-production" in value.lower():
        return True

    return False
