from collections.abc import Generator

from fastapi import Depends, Request
from sqlalchemy.orm import Session

from app.config import Settings, get_settings
from app.db import get_db_session
from app.integrations.homeassistant import HomeAssistantClient
from app.integrations.ticktick import TickTickClient
from app.services.auth import AuthenticatedSession, get_authenticated_session
from app.services.config_page import build_runtime_settings


def get_db() -> Generator[Session, None, None]:
    yield from get_db_session()


def get_app_settings(session: Session = Depends(get_db)) -> Settings:
    return build_runtime_settings(session, get_settings())


def get_homeassistant_client(settings: Settings = Depends(get_app_settings)) -> HomeAssistantClient:
    return HomeAssistantClient(settings)


def get_ticktick_client(settings: Settings = Depends(get_app_settings)) -> TickTickClient:
    return TickTickClient(settings)


def get_current_auth_session(
    request: Request,
    session: Session = Depends(get_db),
    settings: Settings = Depends(get_app_settings),
) -> AuthenticatedSession | None:
    raw_token = request.cookies.get(settings.auth_session_cookie_name)
    return get_authenticated_session(session, raw_token=raw_token)
