"""
Configuration module for FactorDB
"""

from enum import Enum
from dataclasses import dataclass, field
from typing import Optional, Dict, Any
import os
from dotenv import load_dotenv

load_dotenv()


class AssetType(Enum):
    """Asset types supported by FactorDB"""
    STOCK = "stk"
    ETF = "etf"


class FactorType(Enum):
    """Factor frequency types"""
    DAILY = "daily"  # Low/mid frequency daily factors
    HIGH_FREQ = "hf"  # High frequency factors


@dataclass
class FactorDBConfig:
    """Configuration for FactorDB"""

    # Database connection settings
    db_host: str = field(default_factory=lambda: os.getenv("DB_HOST", "localhost"))
    db_port: int = field(default_factory=lambda: int(os.getenv("DB_PORT", 9000)))
    db_user: str = field(default_factory=lambda: os.getenv("DB_USER", "default"))
    db_password: str = field(default_factory=lambda: os.getenv("DB_PASSWORD", ""))

    # Database names for different factor types
    stock_factor_db: str = "stk_factors"
    etf_factor_db: str = "etf_factors"
    hf_stock_factor_db: str = "hf_stk_factors"
    hf_etf_factor_db: str = "hf_etf_factors"

    # Source data databases
    stock_data_db: str = "stocks"
    etf_data_db: str = "etf"

    # Table names
    stock_daily_table: str = "daily_adj_tushare"
    stock_basic_table: str = "daily_basic_tushare"
    etf_daily_table: str = "etf_daily_tushare"

    # Factor evaluation settings
    eval_start_date: str = "2010-01-01"  # IC calculation start date
    recent_5y_offset: int = 5  # Years for 5-year metrics
    recent_1y_offset: int = 1  # Years for 1-year metrics

    # Grouping settings for factor evaluation
    group_counts: tuple = (5, 10, 15)  # Number of groups for sorting

    # Default timezone for high-frequency data
    default_timezone: str = "Asia/Shanghai"

    def get_db_config(
        self,
        asset_type: Optional[AssetType] = None,
        factor_type: Optional[FactorType] = None,
        database: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Get database connection configuration.

        Args:
            asset_type: Asset type (STOCK or ETF) - used to determine database
            factor_type: Factor frequency type (DAILY or HIGH_FREQ) - used to determine database
            database: Explicit database name (overrides asset_type/factor_type)

        Returns:
            Dictionary with database connection settings including 'database' key
        """
        config = {
            "host": self.db_host,
            "port": self.db_port,
            "user": self.db_user,
            "password": self.db_password,
        }

        # Determine database name
        if database is not None:
            config["database"] = database
        elif asset_type is not None and factor_type is not None:
            config["database"] = self.get_factor_db_name(asset_type, factor_type)
        else:
            # Default to stock factors database
            config["database"] = self.stock_factor_db

        return config

    def get_factor_db_name(self, asset_type: AssetType, factor_type: FactorType) -> str:
        """Get the database name for a specific factor type"""
        if asset_type == AssetType.STOCK:
            if factor_type == FactorType.HIGH_FREQ:
                return self.hf_stock_factor_db
            return self.stock_factor_db
        else:  # ETF
            if factor_type == FactorType.HIGH_FREQ:
                return self.hf_etf_factor_db
            return self.etf_factor_db

    def get_factor_id_prefix(self, asset_type: AssetType, factor_type: FactorType) -> str:
        """Get the factor ID prefix for a specific factor type"""
        if factor_type == FactorType.HIGH_FREQ:
            return f"HF_{asset_type.value}"
        return f"F_{asset_type.value}"

    def get_source_data_db(self, asset_type: AssetType) -> str:
        """Get source data database name"""
        if asset_type == AssetType.STOCK:
            return self.stock_data_db
        return self.etf_data_db
