import os
from collections.abc import Generator
from contextlib import contextmanager

from sqlmodel import Session

from infrastructure.postgres.config import PostgresConfig
from infrastructure.postgres.engine import make_engine
from orchestration.task_orchestrator import TaskOrchestrator
from repositories.tasks.subtask_postgres_repository import SubTaskPostgresRepository
from repositories.tasks.task_postgres_repository import TaskPostgresRepository


@contextmanager
def default_orchestrator() -> Generator[TaskOrchestrator, None, None]:
    """Yield a TaskOrchestrator wired to a fresh Postgres session.

    Connection params come from os.environ via PostgresConfig.from_env. Each
    handler invocation gets its own session, cleaned up on context exit.
    """
    engine = make_engine(PostgresConfig.from_env(dict(os.environ)))
    with Session(engine) as session:
        yield TaskOrchestrator(
            task_repo=TaskPostgresRepository(session=session),
            subtask_repo=SubTaskPostgresRepository(session=session),
        )
