import os
import logging
from typing import Optional, Dict
from dotenv import load_dotenv


class Config:
    """
    Simple configuration management class for Notion API token and Flask port.
    Can overwrite .env file values when needed.
    """
    
    def __init__(self, env_file_path: str = '.env', notion_token: Optional[str] = None, port: Optional[int] = None):
        """
        Initialize configuration.
        
        Args:
            env_file_path: Path to the .env file
            notion_token: Optional Notion token to override .env value
            port: Optional port to override .env value
        """
        self.env_file_path = env_file_path
        self._load_environment()
        
        # Set configurable parameters
        self.NOTION_TOKEN: Optional[str] = notion_token or os.getenv('NOTION_TOKEN')
        self.PORT: int = port or int(os.getenv('PORT', 5000))
        
        # Update .env file if overrides were provided
        if notion_token:
            self.update_env_value('NOTION_TOKEN', notion_token)
        if port:
            self.update_env_value('PORT', str(port))
        
        # Configure basic logging
        logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
    
    def _load_environment(self) -> None:
        """Load environment variables from .env file if it exists."""
        if os.path.exists(self.env_file_path):
            load_dotenv(self.env_file_path)
    
    def validate_required_config(self) -> None:
        """
        Validate that required configuration values are present.
        
        Raises:
            ValueError: If NOTION_TOKEN is missing
        """
        if not self.NOTION_TOKEN:
            raise ValueError(
                "NOTION_TOKEN environment variable is not set! "
                "Please create a .env file with your Notion integration token: "
                "NOTION_TOKEN=your_notion_integration_token_here"
            )
    
    def update_env_value(self, key: str, value: str) -> None:
        """
        Update a value in the .env file, creating the file if it doesn't exist.
        
        Args:
            key: Environment variable name (NOTION_TOKEN or PORT)
            value: Environment variable value
        """
        env_vars = self._read_env_file()
        env_vars[key] = value
        self._write_env_file(env_vars)
        
        # Update the current environment and instance
        os.environ[key] = value
        if key == 'NOTION_TOKEN':
            self.NOTION_TOKEN = value
        elif key == 'PORT':
            self.PORT = int(value)
    
    def _read_env_file(self) -> Dict[str, str]:
        """Read existing .env file contents."""
        env_vars = {}
        
        if os.path.exists(self.env_file_path):
            with open(self.env_file_path, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if line and not line.startswith('#') and '=' in line:
                        key, value = line.split('=', 1)
                        env_vars[key.strip()] = value.strip()
        
        return env_vars
    
    def _write_env_file(self, env_vars: Dict[str, str]) -> None:
        """Write environment variables to .env file."""
        with open(self.env_file_path, 'w', encoding='utf-8') as f:
            for key, value in env_vars.items():
                f.write(f"{key}={value}\n")
    
    def get_flask_config(self) -> Dict[str, any]:
        """Get Flask application configuration."""
        return {
            'host': '0.0.0.0',
            'port': self.PORT,
            'debug': False
        }
    
    def get_logger(self, name: str) -> logging.Logger:
        """Get a configured logger instance."""
        return logging.getLogger(name)


# Global configuration instance with port override
config = Config(port=27097)
