# services/suppliers/app/core/config.py
"""
Supplier & Procurement Service Configuration
"""

import os
from typing import List
from pydantic import Field
from shared.config.base import BaseServiceSettings


class Settings(BaseServiceSettings):
    """Supplier service settings extending base configuration"""
    
    # Override service-specific settings
    SERVICE_NAME: str = "suppliers-service"
    VERSION: str = "1.0.0"
    APP_NAME: str = "Bakery Supplier Service"
    DESCRIPTION: str = "Supplier and procurement management service"
    
    # API Configuration
    API_V1_STR: str = "/api/v1"
    
    # Database configuration (secure approach - build from components)
    @property
    def DATABASE_URL(self) -> str:
        """Build database URL from secure components"""
        # Try complete URL first (for backward compatibility)
        complete_url = os.getenv("SUPPLIERS_DATABASE_URL")
        if complete_url:
            return complete_url

        # Build from components (secure approach)
        user = os.getenv("SUPPLIERS_DB_USER", "suppliers_user")
        password = os.getenv("SUPPLIERS_DB_PASSWORD", "suppliers_pass123")
        host = os.getenv("SUPPLIERS_DB_HOST", "localhost")
        port = os.getenv("SUPPLIERS_DB_PORT", "5432")
        name = os.getenv("SUPPLIERS_DB_NAME", "suppliers_db")

        return f"postgresql+asyncpg://{user}:{password}@{host}:{port}/{name}"
    
    # Suppliers-specific Redis database
    REDIS_DB: int = Field(default=4, env="SUPPLIERS_REDIS_DB")
    
    # File upload configuration
    MAX_UPLOAD_SIZE: int = 10 * 1024 * 1024  # 10MB
    UPLOAD_PATH: str = Field(default="/tmp/uploads", env="SUPPLIERS_UPLOAD_PATH")
    ALLOWED_FILE_EXTENSIONS: List[str] = [".csv", ".xlsx", ".xls", ".pdf", ".png", ".jpg", ".jpeg"]
    
    # Pagination
    DEFAULT_PAGE_SIZE: int = 50
    MAX_PAGE_SIZE: int = 500
    
    # Price validation
    MIN_UNIT_PRICE: float = 0.01
    MAX_UNIT_PRICE: float = 10000.0
    MIN_ORDER_AMOUNT: float = 1.0
    MAX_ORDER_AMOUNT: float = 100000.0
    
    # Supplier-specific cache TTL
    SUPPLIERS_CACHE_TTL: int = 900  # 15 minutes
    PURCHASE_ORDERS_CACHE_TTL: int = 300  # 5 minutes
    DELIVERIES_CACHE_TTL: int = 180  # 3 minutes
    PRICE_LIST_CACHE_TTL: int = 1800  # 30 minutes
    
    # Purchase order settings
    DEFAULT_PAYMENT_TERMS_DAYS: int = 30
    MAX_PAYMENT_TERMS_DAYS: int = 90
    DEFAULT_DELIVERY_DAYS: int = 3
    MAX_DELIVERY_DAYS: int = 30
    
    # Quality and rating settings
    MIN_QUALITY_RATING: float = 1.0
    MAX_QUALITY_RATING: float = 5.0
    MIN_DELIVERY_RATING: float = 1.0
    MAX_DELIVERY_RATING: float = 5.0
    
    # Lead time settings (in days)
    DEFAULT_LEAD_TIME: int = 3
    MAX_LEAD_TIME: int = 30
    
    # Order approval thresholds
    AUTO_APPROVE_THRESHOLD: float = 500.0  # Amounts below this auto-approve
    MANAGER_APPROVAL_THRESHOLD: float = 2000.0  # Manager approval required
    
    # Communication settings
    ORDER_CONFIRMATION_EMAIL: bool = True
    DELIVERY_NOTIFICATION_EMAIL: bool = True
    QUALITY_ISSUE_EMAIL: bool = True
    
    # Business hours for supplier contact (24h format)
    BUSINESS_HOURS_START: int = 8
    BUSINESS_HOURS_END: int = 18
    
    # Performance Tracking Settings
    PERFORMANCE_TRACKING_ENABLED: bool = Field(default=True, env="PERFORMANCE_TRACKING_ENABLED")
    PERFORMANCE_CALCULATION_INTERVAL_MINUTES: int = Field(default=60, env="PERFORMANCE_CALCULATION_INTERVAL")
    PERFORMANCE_CACHE_TTL: int = Field(default=300, env="PERFORMANCE_CACHE_TTL")  # 5 minutes
    
    # Performance Thresholds
    EXCELLENT_DELIVERY_RATE: float = 95.0
    GOOD_DELIVERY_RATE: float = 90.0
    ACCEPTABLE_DELIVERY_RATE: float = 85.0
    POOR_DELIVERY_RATE: float = 80.0
    
    EXCELLENT_QUALITY_RATE: float = 98.0
    GOOD_QUALITY_RATE: float = 95.0
    ACCEPTABLE_QUALITY_RATE: float = 90.0
    POOR_QUALITY_RATE: float = 85.0
    
    # Alert Settings
    ALERTS_ENABLED: bool = Field(default=True, env="SUPPLIERS_ALERTS_ENABLED")
    ALERT_EVALUATION_INTERVAL_MINUTES: int = Field(default=15, env="ALERT_EVALUATION_INTERVAL")
    ALERT_RETENTION_DAYS: int = Field(default=365, env="ALERT_RETENTION_DAYS")
    
    # Critical alert thresholds
    CRITICAL_DELIVERY_DELAY_HOURS: int = 24
    CRITICAL_QUALITY_REJECTION_RATE: float = 10.0
    HIGH_COST_VARIANCE_PERCENTAGE: float = 15.0
    
    # Dashboard Settings
    DASHBOARD_CACHE_TTL: int = Field(default=180, env="SUPPLIERS_DASHBOARD_CACHE_TTL")  # 3 minutes
    DASHBOARD_REFRESH_INTERVAL: int = Field(default=300, env="DASHBOARD_REFRESH_INTERVAL")  # 5 minutes
    
    # Performance Analytics
    DEFAULT_ANALYTICS_PERIOD_DAYS: int = 30
    MAX_ANALYTICS_PERIOD_DAYS: int = 365
    SCORECARD_GENERATION_DAY: int = 1  # Day of month to generate scorecards
    
    # Notification Settings
    NOTIFICATION_EMAIL_ENABLED: bool = Field(default=True, env="NOTIFICATION_EMAIL_ENABLED")
    NOTIFICATION_WEBHOOK_ENABLED: bool = Field(default=False, env="NOTIFICATION_WEBHOOK_ENABLED")
    NOTIFICATION_WEBHOOK_URL: str = Field(default="", env="NOTIFICATION_WEBHOOK_URL")
    
    # Business Model Detection
    ENABLE_BUSINESS_MODEL_DETECTION: bool = Field(default=True, env="ENABLE_BUSINESS_MODEL_DETECTION")
    CENTRAL_BAKERY_THRESHOLD_SUPPLIERS: int = Field(default=20, env="CENTRAL_BAKERY_THRESHOLD_SUPPLIERS")
    INDIVIDUAL_BAKERY_THRESHOLD_SUPPLIERS: int = Field(default=10, env="INDIVIDUAL_BAKERY_THRESHOLD_SUPPLIERS")
    
    # Performance Report Settings
    AUTO_GENERATE_MONTHLY_REPORTS: bool = Field(default=True, env="AUTO_GENERATE_MONTHLY_REPORTS")
    AUTO_GENERATE_QUARTERLY_REPORTS: bool = Field(default=True, env="AUTO_GENERATE_QUARTERLY_REPORTS")
    REPORT_EXPORT_FORMATS: List[str] = ["pdf", "excel", "csv"]


# Global settings instance
settings = Settings()