"""Dagster resources for external connections."""

import os
from dagster import ConfigurableResource, resource
import httpx
from pymongo import MongoClient


class EgrulAgentResource(ConfigurableResource):
    """Resource for calling EGRUL agent API."""

    base_url: str = "http://egrul-agent:8000"

    def fetch_company(self, inn: str) -> dict:
        """Fetch company data from EGRUL agent."""
        with httpx.Client(timeout=300.0) as client:
            # Use direct EGRUL API endpoint (creates fresh MCP connection)
            response = client.post(
                f"{self.base_url}/api/egrul",
                json={"inn": inn},
            )
            response.raise_for_status()
            return response.json()


class PostgresResource(ConfigurableResource):
    """Resource for Postgres connection."""

    host: str = "postgres"
    port: int = 5432
    user: str = "postgres"
    password: str = ""
    database: str = "optovia"

    def get_connection_string(self) -> str:
        return f"postgresql://{self.user}:{self.password}@{self.host}:{self.port}/{self.database}"


class MongoResource(ConfigurableResource):
    """Resource for MongoDB connection."""

    uri: str
    database: str = "optovia"
    collection: str = "company_documents"

    def get_collection(self, collection_name: str | None = None):
        """Get MongoDB collection. Use collection_name to override default."""
        client = MongoClient(self.uri)
        name = collection_name or self.collection
        return client[self.database][name]


class KycPostgresResource(ConfigurableResource):
    """Resource for KYC Postgres connection (read kyc_monitoring)."""

    host: str = "kyc-db"
    port: int = 5432
    user: str = "postgres"
    password: str = ""
    database: str = "kyc"

    def get_connection_string(self) -> str:
        return f"postgresql://{self.user}:{self.password}@{self.host}:{self.port}/{self.database}"


# Resource instances
egrul_agent_resource = EgrulAgentResource(
    base_url=os.getenv("EGRUL_AGENT_URL", "http://egrul-agent:8000")
)

postgres_resource = PostgresResource(
    host=os.getenv("POSTGRES_HOST", "postgres"),
    port=int(os.getenv("POSTGRES_PORT", "5432")),
    user=os.getenv("POSTGRES_USER", "postgres"),
    password=os.getenv("POSTGRES_PASSWORD", ""),
    database=os.getenv("POSTGRES_DB", "optovia"),
)

mongo_resource = MongoResource(
    uri=os.getenv("MONGODB_URI", ""),
    database=os.getenv("MONGODB_DB", "optovia"),
    collection=os.getenv("MONGODB_COLLECTION", "company_documents"),
)

kyc_postgres_resource = KycPostgresResource(
    host=os.getenv("KYC_POSTGRES_HOST", "kyc-db"),
    port=int(os.getenv("KYC_POSTGRES_PORT", "5432")),
    user=os.getenv("KYC_POSTGRES_USER", "postgres"),
    password=os.getenv("KYC_POSTGRES_PASSWORD", ""),
    database=os.getenv("KYC_POSTGRES_DB", "kyc"),
)
