from __future__ import annotations

import logging

from .agent import NullIntentParser, NullTaskPlanner, OpenAIIntentParser, OpenAITaskPlanner
from .config import Settings
from .mac_client import MacControlClient
from .executor import LocalCommandExecutor
from .control import ControlBackend
from .notifier import TelegramNotifier
from .state_store import StateStore
from .telegram_bot import TelegramBotService
from .transcriber import NullVoiceTranscriber, OpenAIVoiceTranscriber
from .worker import WorkerController


def main() -> None:
    settings = Settings()
    logging.basicConfig(
        level=getattr(logging, settings.codexbot_log_level.upper(), logging.INFO),
        format="%(asctime)s %(levelname)s %(name)s %(message)s",
    )
    logging.getLogger("httpx").disabled = True
    logging.getLogger("httpcore").disabled = True

    intent_parser = (
        OpenAIIntentParser(settings.openai_api_key, settings.codexbot_intent_model)
        if settings.openai_api_key
        else NullIntentParser()
    )
    transcriber = (
        OpenAIVoiceTranscriber(
            settings.openai_api_key,
            settings.codexbot_transcribe_model,
            settings.codexbot_transcribe_language,
        )
        if settings.openai_api_key
        else NullVoiceTranscriber()
    )
    backend: ControlBackend
    if settings.codexbot_mac_service_url and settings.codexbot_mac_service_token:
        backend = MacControlClient(
            base_url=settings.codexbot_mac_service_url,
            token=settings.codexbot_mac_service_token,
            timeout_seconds=settings.codexbot_mac_service_timeout_seconds,
        )
    else:
        store = StateStore(settings.codexbot_state_path)
        planner = (
            OpenAITaskPlanner(settings.openai_api_key, settings.codexbot_agent_model)
            if settings.openai_api_key
            else NullTaskPlanner()
        )
        executor = LocalCommandExecutor(
            workdir=settings.codexbot_workdir,
            allowed_commands=settings.allowed_commands,
            max_output_chars=settings.codexbot_max_output_chars,
        )
        notifier = TelegramNotifier(settings.telegram_bot_token, settings.allowed_user_ids)
        backend = WorkerController(
            store,
            executor,
            planner,
            notifier,
            poll_seconds=settings.codexbot_worker_poll_seconds,
        )
    bot = TelegramBotService(settings, backend, transcriber, intent_parser)
    bot.run()


if __name__ == "__main__":
    main()
