from __future__ import annotations

import logging
import os
from importlib import resources
from importlib.util import find_spec
from pathlib import Path

from dynaconf import Dynaconf
from analogai.foundation.common.utils.config_base import ConfigBase
from analogai.foundation.common.utils.env_utils import load_envs_in_order, get_loaded_env_paths


load_envs_in_order()
if not os.getenv("ENVIRONMENT"):
    os.environ["ENVIRONMENT"] = "development"

def _package_exists(package: str) -> bool:
    try:
        return find_spec(package) is not None
    except ModuleNotFoundError:
        return False


def _local_config_dir() -> Path:
    return Path(__file__).resolve().parent / "config"


def _resolve_package_dir(package: str) -> Path | None:
    try:
        return Path(str(resources.files(package)))
    except (ModuleNotFoundError, FileNotFoundError):
        return None


def _resolve_config_dir() -> Path:
    explicit_dir = os.getenv("APP_CONFIG_DIR") or os.getenv("DEEPTHINK_CONFIG_DIR")
    if explicit_dir:
        return Path(explicit_dir)

    package = (
        os.getenv("APP_CONFIG_PACKAGE")
        or os.getenv("DEEPTHINK_CONFIG_PACKAGE")
        or "analogai.deepthink.config"
    )
    if _package_exists(package):
        resolved = _resolve_package_dir(package)
        if resolved is not None:
            return resolved
    resolved = _resolve_package_dir("analogai.foundation.config")
    return resolved or _local_config_dir()


def _resolve_config_files() -> tuple[list[str], str | None]:
    config_dir = _resolve_config_dir()
    default_path = config_dir / "default.yaml"
    schema_candidate = config_dir / "schema.yaml"
    settings_files: list[str] = []
    schema_path: str | None = None
    if default_path.exists():
        settings_files.append(str(default_path))
    if schema_candidate.exists():
        schema_path = str(schema_candidate)
    if not settings_files:
        fallback_dir = _local_config_dir()
        fallback_default = fallback_dir / "default.yaml"
        fallback_schema = fallback_dir / "schema.yaml"
        if fallback_default.exists():
            settings_files.append(str(fallback_default))
        if fallback_schema.exists():
            schema_path = str(fallback_schema)
    return settings_files, schema_path


_SETTINGS_FILES, _SCHEMA_PATH = _resolve_config_files()


settings = Dynaconf(
    envvar_prefix=False,
    settings_files=_SETTINGS_FILES,
    defaults={
        "ENVIRONMENT": "development",
    },
    environments=False,
    load_dotenv=False,
    validate_on_update=True,
)
config = ConfigBase(settings, schema_path=_SCHEMA_PATH) if _SCHEMA_PATH else ConfigBase(settings)

try:
    message = f"[FoundationSettings] ENVIRONMENT={os.getenv('ENVIRONMENT')}"
    print(message)
    logging.getLogger(__name__).info(message)
except Exception:
    pass

__all__ = ["settings", "config"]
