import os
from functools import lru_cache
from pathlib import Path
from pydantic_settings import BaseSettings, SettingsConfigDict
from typing import Optional

from utils.logger import setup_logger

logger = setup_logger()


def resolve_env_file() -> Optional[str]:
    env = os.getenv("ENVIRONMENT", "local")

    backend_dir = Path(__file__).resolve().parents[1]

    if env == "local":
        env_file = backend_dir / ".env"
        print("USING ENV FILE:", env_file)
        logger.debug("USING ENV FILE:", env_file)
        return str(env_file)

    if env == "test":
        env_file = backend_dir / ".env.test"
        logger.debug("USING ENV FILE:", env_file)
        return str(env_file)

    # prod = no env file
    return None


class Settings(BaseSettings):
    API_KEY: str = "changeme"
    API_KEY_NAME: str = "X-API-KEY"
    SECRET_KEY: str = "changeme"
    ENVIRONMENT: str = "changeme"
    DATA_BUCKET: str = "changeme"
    PLAN_TRIGGER_BUCKET: str = "changeme"
    ENGINE_SQS_URL: str = "changeme"
    CATEGORISATION_SQS_URL: str = "changeme"
    PASHUB_TO_ARA_SQS_URL: str = "changeme"
    MAGICPLAN_SQS_URL: str = "changeme"
    POSTCODE_SPLITTER_SQS_URL: str = "changeme"
    COMBINER_SQS_URL: str = "changeme"

    # Third parties
    EPC_AUTH_TOKEN: str = "changeme"
    OPEN_EPC_API_TOKEN: str = "changeme"
    GOOGLE_SOLAR_API_KEY: str = "changeme"
    MAGICPLAN_CUSTOMER_ID: str = "changeme"
    MAGICPLAN_API_KEY: str = "changeme"

    # Database settings
    DB_HOST: str = "changeme"
    DB_PASSWORD: str = "changeme"
    DB_USERNAME: str = "changeme"
    DB_PORT: str = "changeme"
    DB_NAME: str = "changeme"

    # Prediction buckets
    SAP_PREDICTIONS_BUCKET: str = "changeme"
    CARBON_PREDICTIONS_BUCKET: str = "changeme"
    HEAT_PREDICTIONS_BUCKET: str = "changeme"
    HEATING_KWH_PREDICTIONS_BUCKET: str = "changeme"
    HOTWATER_KWH_PREDICTIONS_BUCKET: str = "changeme"
    SAP_BASELINE_PREDICTIONS_BUCKET: str = "changeme"
    CARBON_BASELINE_PREDICTIONS_BUCKET: str = "changeme"
    HEAT_BASELINE_PREDICTIONS_BUCKET: str = "changeme"

    # Other S3 buckts
    ENERGY_ASSESSMENTS_BUCKET: str = "changeme"

    ORDNANCE_SURVEY_API_KEY: str = "changeme"

    HUBSPOT_API_KEY: Optional[str] = None
    # Sharepoint
    SHAREPOINT_CLIENT_ID: Optional[str] = None
    SHAREPOINT_CLIENT_SECRET: Optional[str] = None
    SHAREPOINT_TENANT_ID: Optional[str] = None
    DOMNA_SHAREPOINT_ID: Optional[str] = None
    OSMOSIS_ACD_SHAREPOINT_ID: Optional[str] = None
    PRIVATE_PAY_SHAREPOINT_ID: Optional[str] = None
    SOCIAL_HOUSING_WAVE_3_SHAREPOINT_ID: Optional[str] = None
    OPENAI_API_KEY: Optional[str] = None

    # Pas Hub
    PASHUB_EMAIL: Optional[str] = None
    PASHUB_PASSWORD: Optional[str] = None

    # Optional AWS creds (only required in local)
    AWS_ACCESS_KEY_ID: Optional[str] = None
    AWS_SECRET_KEY_ID: Optional[str] = None
    AWS_DEFAULT_REGION: Optional[str] = None

    model_config = SettingsConfigDict(
        env_file=resolve_env_file(),
        env_file_encoding="utf-8",
    )


@lru_cache()
def get_settings():
    return Settings()


@lru_cache()
def get_prediction_buckets():
    return {
        "sap_change_predictions": get_settings().SAP_PREDICTIONS_BUCKET,
        "heat_demand_predictions": get_settings().HEAT_PREDICTIONS_BUCKET,
        "carbon_change_predictions": get_settings().CARBON_PREDICTIONS_BUCKET,
        "heating_kwh_predictions": get_settings().HEATING_KWH_PREDICTIONS_BUCKET,
        "hotwater_kwh_predictions": get_settings().HOTWATER_KWH_PREDICTIONS_BUCKET,
        # Score model - SAP re-baselining model
        "retrofit_sap_baseline_predictions": get_settings().SAP_BASELINE_PREDICTIONS_BUCKET,
        "retrofit_carbon_baseline_predictions": get_settings().CARBON_BASELINE_PREDICTIONS_BUCKET,
        "retrofit_heat_baseline_predictions": get_settings().HEAT_BASELINE_PREDICTIONS_BUCKET,
    }
