#!/usr/bin/python3

"""
config.py

Secure configuration module for RAG gene discovery pipeline.

- Loads all credentials, paths, and model settings from environment variables or .env file.
- Hides sensitive info like Neo4j credentials and NCBI email.
- Supports local or Docker environment.
- Ensures required directories exist.

Author:
    Manish Kumar
"""

import os
import stat
from dotenv import load_dotenv

# Load .env file if exists
load_dotenv()

# ----------------------------
# Workspace and Base Paths
# ----------------------------
if os.path.exists("/workspace"):
    WORKSPACE_DIR = "/workspace"
else:
    WORKSPACE_DIR = os.getcwd()

os.makedirs(WORKSPACE_DIR, exist_ok=True)

BASE_PATH = os.getenv("PUBMED_BASE_PATH", os.path.join(WORKSPACE_DIR, "data", "PubMed"))

# ----------------------------
# Derived Folders
# ----------------------------
ABSTRACT_FOLDER = os.path.join(BASE_PATH, "Abstracts")
METADATA_FOLDER = os.path.join(BASE_PATH, "Metadata")
PDF_FOLDER = os.path.join(BASE_PATH, "PDFs")
INDEX_FOLDER = os.path.join(BASE_PATH, "Index")

# Ensure directories exist
for folder in [ABSTRACT_FOLDER, METADATA_FOLDER, PDF_FOLDER, INDEX_FOLDER]:
    os.makedirs(folder, exist_ok=True)
    os.chmod(folder, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  # 777 for testing

# ----------------------------
# Index Files
# ----------------------------
INDEX_FILE = os.path.join(INDEX_FOLDER, "pubmed_index.faiss")
ID_MAP_FILE = os.path.join(INDEX_FOLDER, "pmid_map.json")

# ----------------------------
# Model and Retrieval Parameters
# ----------------------------
MODEL_NAME = os.getenv("OLLAMA_MODEL", "mxbai-embed-large")
CHAT_MODEL = os.getenv("CHAT_MODEL", "deepseek-r1:latest")
TOP_K = int(os.getenv("TOP_K", 15))
USE_GPU = os.getenv("USE_GPU", "True").lower() in ("true", "1", "yes")

# ----------------------------
# Neo4j Knowledge Graph Config (Sensitive, use .env)
# ----------------------------
NEO4J_URI = os.getenv("NEO4J_URI")
NEO4J_USER = os.getenv("NEO4J_USER")
NEO4J_PASSWORD = os.getenv("NEO4J_PASSWORD")

# ----------------------------
# NCBI Entrez Configuration
# ----------------------------
ENTREZ_EMAIL = os.getenv("NCBI_EMAIL")

# ----------------------------
# Debug prints (optional)
# ----------------------------
if os.getenv("DEBUG_CONFIG", "True").lower() in ("true", "1", "yes"):
    print("Workspace directory:", WORKSPACE_DIR)
    print("Base path:", BASE_PATH)
    print("Abstract folder:", ABSTRACT_FOLDER)
    print("Index file:", INDEX_FILE)
