#!/usr/bin/env python3
"""
Configuration management for ACH file processing pipeline.
Loads and validates environment variables.
"""

import os
from pathlib import Path
from logging_config import get_logger

logger = get_logger(__name__)


class Config:
    """Application configuration from environment variables."""

    def __init__(self):
        """Initialize configuration from environment."""
        self._validate_env_file()
        self._load_database_config()
        self._load_sftp_config()
        self._load_processing_config()

    def _validate_env_file(self):
        """Check if .env file exists."""
        if not Path('.env').exists():
            logger.warning(".env file not found. Using environment variables or defaults.")
       
    def _load_database_config(self):
        """Load database configuration."""
        self.db_user = os.getenv('DB_USER', 'pacs_db')
        self.db_password = os.getenv('DB_PASSWORD', 'pacs_db')
        self.db_host = os.getenv('DB_HOST', 'testipksdb.c7q7defafeea.ap-south-1.rds.amazonaws.com')
        self.db_port = int(os.getenv('DB_PORT', '1521'))
        self.db_service_name = os.getenv('DB_SERVICE_NAME', 'IPKSDB')
        self.db_pool_min = int(os.getenv('DB_POOL_MIN', '2'))
        self.db_pool_max = int(os.getenv('DB_POOL_MAX', '10'))

    def _load_sftp_config(self):
        """Load SFTP configuration."""
        self.sftp_host = os.getenv('SFTP_HOST', '43.225.3.224')
        self.sftp_port = int(os.getenv('SFTP_PORT', '4650'))
        self.sftp_username = os.getenv('SFTP_USERNAME', 'ipkssftp')
        self.sftp_password = os.getenv('SFTP_PASSWORD', 'CqBx@j6G9vqNW#1')
        self.sftp_base_path = os.getenv('SFTP_BASE_PATH', '/home/ipks/IPKS_FILES/REPORTS')

    def _load_processing_config(self):
        """Load processing configuration."""
        self.poll_interval_minutes = int(os.getenv('POLL_INTERVAL_MINUTES', '30'))
        self.batch_size = int(os.getenv('BATCH_SIZE', '100'))
        self.bank_codes = self._parse_bank_codes()
        self.log_level = os.getenv('LOG_LEVEL', 'INFO')

    def _parse_bank_codes(self):
        """Parse bank codes from comma-separated environment variable."""
        codes_str = os.getenv('BANK_CODES', '0001,0002,0003,0004,0005,0006,0007,0009,0012,0013,0014,0015,0016,0017,0018,0020,0021')
        return [code.strip() for code in codes_str.split(',') if code.strip()]

    def get_db_connection_string(self):
        """Generate Oracle connection string."""
        return f"{self.db_user}/{self.db_password}@{self.db_host}:{self.db_port}/{self.db_service_name}"

    def validate(self):
        """Validate critical configuration."""
        if not self.db_user or not self.db_password:
            raise ValueError("Database credentials not configured")
        if not self.sftp_username:
            logger.warning("SFTP username not configured")
        if not self.bank_codes:
            raise ValueError("No bank codes configured")
        logger.info(f"Configuration validated. Bank codes: {', '.join(self.bank_codes)}")


# Global config instance
config = None


def get_config():
    """Get or create global config instance."""
    global config
    if config is None:
        config = Config()
    return config


if __name__ == '__main__':
    cfg = get_config()
    cfg.validate()
    print(f"Bank Codes: {cfg.bank_codes}")
    print(f"SFTP Host: {cfg.sftp_host}:{cfg.sftp_port}")
    print(f"Database: {cfg.db_host}:{cfg.db_port}/{cfg.db_service_name}")
    print(f"Poll Interval: {cfg.poll_interval_minutes} minutes")
