File size: 1,597 Bytes
fa4fc8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74f026f
 
 
 
 
 
 
 
fa4fc8b
ecb9d4e
 
 
 
 
 
 
 
 
fa4fc8b
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import os
from dotenv import load_dotenv
from pymongo import MongoClient
import certifi
from datetime import datetime

load_dotenv()


def get_collections():
    """Return a dict with MongoDB collections used by the app.
    Loads `MONGO_URI` from environment and connects with TLS CA validation.
    Raises RuntimeError if `MONGO_URI` is missing.
    """
    mongo_uri = os.getenv("MONGO_URI")
    if not mongo_uri:
        raise RuntimeError("MONGO_URI is not set in the environment")

    # Check if it's a cloud cluster (mongodb+srv or contains mongodb.net)
    # Use SSL for cloud clusters, skip SSL for self-hosted instances
    if "mongodb+srv" in mongo_uri or "mongodb.net" in mongo_uri:
        client = MongoClient(mongo_uri, tlsCAFile=certifi.where())
    else:
        # Self-hosted MongoDB - connect without SSL
        client = MongoClient(mongo_uri)
    
    db = client["AgriPredict"]
    
    # Create indexes for better query performance (safe to call multiple times)
    try:
        db["WhiteSesame"].create_index([("Reported Date", -1)])
        db["WhiteSesame"].create_index([("State Name", 1), ("Reported Date", -1)])
        db["WhiteSesame"].create_index([("Market Name", 1), ("Reported Date", -1)])
    except Exception:
        pass  # Indexes might already exist
    
    return {
        "collection": db["WhiteSesame"],
        "best_params_collection": db["BestParams"],
        "best_params_collection_1m": db["BestParams_1m"],
        "best_params_collection_3m": db["BestParams_3m"],
        "impExp": db["impExp"],
        "users_collection": db["user"],
    }