#!/usr/bin/env python3
"""
Server configuration management for GNSS Guard Server
Loads configuration from environment variables
"""

import os
import sys
from pathlib import Path
from typing import Optional
from pydantic_settings import BaseSettings
from pydantic import field_validator


class ServerConfig(BaseSettings):
    """Server configuration loaded from environment variables"""
    
    # Server settings
    server_host: str = "0.0.0.0"
    server_port: int = 8000
    debug: bool = False
    
    # Database settings (PostgreSQL) - REQUIRED, no insecure default
    database_url: str
    
    # Security settings
    secret_key: str = "change-this-in-production-to-a-random-secret-key"
    session_expire_minutes: int = 1440  # 24 hours
    
    # Web UI authentication - REQUIRED, no insecure defaults
    # Must be set via environment variables GNSS_SERVER_WEB_USERNAME and GNSS_SERVER_WEB_PASSWORD
    web_username: str
    web_password: str
    
    @field_validator('web_password')
    @classmethod
    def password_strength(cls, v: str) -> str:
        """Ensure password meets minimum security requirements"""
        if len(v) < 10:
            raise ValueError('Password must be at least 10 characters long')
        if v.lower() in ['password', 'admin', 'test', '123456', 'tototheo']:
            raise ValueError('Password is too common/weak')
        return v
    
    # Validation settings
    stale_threshold_seconds: int = 60  # Data older than this is considered stale
    
    # Asset offline detection
    asset_offline_seconds: int = 120  # Consider asset offline after this many seconds without updates
    
    # Data retention
    validation_history_days: int = 90  # Keep 90 days of validation history
    
    # Domain for SSL (optional)
    server_domain: Optional[str] = None
    
    # Telegram notification settings (optional)
    telegram_bot_token: Optional[str] = None
    telegram_chat_id: Optional[str] = None  # Default chat ID for all assets
    
    @property
    def telegram_enabled(self) -> bool:
        """Check if Telegram notifications are configured"""
        return bool(self.telegram_bot_token and self.telegram_chat_id)
    
    class Config:
        env_file = ".env"
        env_prefix = "GNSS_SERVER_"
        case_sensitive = False


def get_config() -> ServerConfig:
    """Get server configuration instance"""
    return ServerConfig()

