from dotenv import load_dotenv, find_dotenv
import os
import sys
from importlib.util import find_spec
from pathlib import Path
from analogai.foundation.common.enums.relationship_type_positivity_threshold import RelationshipTypePositivityThreshold


def _find_project_root(start: Path) -> Path | None:
    current = start
    while True:
        if (current / "pyproject.toml").exists() or (current / ".env").exists():
            return current
        if current.parent == current:
            return None
        current = current.parent


def _find_module_root(module_name: str) -> Path | None:
    spec = find_spec(module_name)
    if spec and spec.origin:
        return _find_project_root(Path(spec.origin).resolve())
    return None


def _ordered_env_roots() -> list[Path]:
    roots: list[Path] = []
    env_file = os.getenv("ENV_FILE")
    if env_file:
        env_path = Path(env_file).expanduser().resolve()
        roots.append(env_path.parent)

    argv0 = Path(sys.argv[0]).expanduser().resolve() if sys.argv and sys.argv[0] else None
    if argv0 and argv0.exists():
        entry_root = _find_project_root(argv0.parent)
        if entry_root:
            roots.append(entry_root)

    deepthink_root = _find_module_root("deepthink")
    if deepthink_root:
        roots.append(deepthink_root)

    foundation_root = _find_project_root(Path(__file__).resolve())
    if foundation_root:
        roots.append(foundation_root)

    seen: set[Path] = set()
    ordered: list[Path] = []
    for root in roots:
        if root not in seen:
            ordered.append(root)
            seen.add(root)
    return ordered


def _load_envs_in_order() -> None:
    for root in _ordered_env_roots():
        env_path = root / ".env"
        if env_path.exists():
            load_dotenv(env_path, override=False)


_load_envs_in_order()


def get_required_env(key: str) -> str:
    value = os.getenv(key)
    if value is None:
        raise ValueError(f"Required environment variable '{key}' is not set")
    return value


def get_optional_env(key: str, default: str) -> str:
    return os.getenv(key, default)


ENVIRONMENT = os.getenv('ENVIRONMENT', 'production')

if ENVIRONMENT not in ['development', 'production']:
    raise ValueError(
        "Environment variable ENVIRONMENT must be one of: development or production"
    )
print(f"Environment is set to {ENVIRONMENT} at Foundation")

DEBUG = os.getenv('DEBUG', 'true').lower() == 'true'
LEMMATIZATION_ENABLED = os.getenv('LEMMATIZATION_ENABLED', 'false').lower() == 'true'
SIMILARITY_CUTOFF = float(os.getenv('SIMILARITY_CUTOFF', '0.4'))
USE_VECTOR_SEARCH = os.getenv('USE_VECTOR_SEARCH', 'false').lower() == 'true'
print(f"USE_VECTOR_SEARCH is set to {USE_VECTOR_SEARCH} threshold is {SIMILARITY_CUTOFF}")

RELATIONSHIP_TYPE_POSITIVITY_THRESHOLD_NEGATIVE = float(
    os.getenv(
        'RELATIONSHIP_TYPE_POSITIVITY_THRESHOLD_NEGATIVE',
        str(RelationshipTypePositivityThreshold.NEGATIVE.value),
    )
)
RELATIONSHIP_TYPE_POSITIVITY_THRESHOLD_UNCERTAIN = float(
    os.getenv(
        'RELATIONSHIP_TYPE_POSITIVITY_THRESHOLD_UNCERTAIN',
        str(RelationshipTypePositivityThreshold.UNCERTAIN.value),
    )
)

BELIEF_QUERY_MODIFIER_STRATEGY = os.getenv('BELIEF_QUERY_MODIFIER_STRATEGY', 'exact').lower()
if BELIEF_QUERY_MODIFIER_STRATEGY not in ['exact', 'ignore']:
    raise ValueError("BELIEF_QUERY_MODIFIER_STRATEGY must be 'exact' or 'ignore'")

MONGODB_URI = os.getenv('MONGODB_URI')
MONGODB_DATABASE = os.getenv('MONGODB_DATABASE')

NEO4J_URI = os.getenv('NEO4J_URI')
NEO4J_USER = os.getenv('NEO4J_USER')
NEO4J_PASSWORD = os.getenv('NEO4J_PASSWORD')
NEO4J_DATABASE = os.getenv('NEO4J_DATABASE')
NEO4J_IS_ENCRYPTED = os.getenv('NEO4J_IS_ENCRYPTED', 'false')
