import os
from pathlib import Path
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))


class DIContainer:
    def __init__(self):
        from . import AppConfig
        from repositories import MinIOStorageRepository
        from services import (
            AudioService, ChatService, HealthService, ResponseService, 
            ResponseManager, OpenAIService, AgentService, ConnectionPool, 
            LanguageSegmentationService, DataIngestionService, MCQService,
            PGVectorService, ChatDatabaseService
        )

        self.config = AppConfig.from_env()
        self.storage_repo = MinIOStorageRepository(self.config)
        self.response_manager = ResponseManager()
        
        # Initialize OpenAI and Agent services
        self.openai_service = OpenAIService()

        self.pool_handler = ConnectionPool(
            dbname=os.getenv("POSTGRES_DB"),
            user=os.getenv("POSTGRES_USER"),
            password=os.getenv("POSTGRES_PASSWORD"),
            host=os.getenv("DB_HOST"),
            port=int(os.getenv("DB_PORT"))
        )
        print(os.getenv("DB_HOST"), os.getenv("POSTGRES_DB"), os.getenv("POSTGRES_USER"))
        self.chat_db_service = ChatDatabaseService(self.pool_handler)
        self.pgvector_service = PGVectorService(self.pool_handler)
        self.agent_service = AgentService(
            use_pgvector=True, 
            pgvector=self.pgvector_service,
            db_service=self.chat_db_service
        )
        self.mcq_service = MCQService(self.pgvector_service, self.chat_db_service)

        self.data_ingestion_service = DataIngestionService(pool_handler=self.pool_handler)


        # Initialize services
        self.audio_service = AudioService(self.storage_repo, self.config.minio_bucket)
        self.segmentation_service = LanguageSegmentationService()
        self.chat_service = ChatService(
            self.storage_repo, 
            self.response_manager, 
            self.config,
            self.openai_service,
            self.agent_service,
            self.segmentation_service
        )
        self.response_service = ResponseService(self.response_manager, self.audio_service)
        self.health_service = HealthService(self.storage_repo, self.config)