"""Shared sync helpers for CLI commands."""

from __future__ import annotations

from collections.abc import Callable

from ..client import connect, fetch_history, sync_all
from ..db import MessageDB


def _parse_chat(chat: str) -> str | int:
    try:
        return int(chat)
    except ValueError:
        return chat


async def sync_all_dialogs(
    *,
    limit: int,
    on_chat_done: Callable[[str, int, int], None] | None = None,
) -> dict[str, int]:
    """Sync all dialogs available to the current Telegram account."""
    with MessageDB() as db:
        async with connect() as client:
            return await sync_all(client, db, limit_per_chat=limit, on_chat_done=on_chat_done)


async def sync_chat_dialog(
    chat: str,
    *,
    limit: int,
    on_progress: Callable[[int], None] | None = None,
) -> int:
    """Sync a single chat into the local database."""
    with MessageDB() as db:
        chat_id = db.resolve_chat_id(chat)
        last_id = db.get_last_msg_id(chat_id) if chat_id else 0
        async with connect() as client:
            return await fetch_history(
                client,
                _parse_chat(chat),
                limit=limit,
                db=db,
                on_progress=on_progress,
                min_id=last_id or 0,
            )
