from __future__ import annotations

from lark_oapi.api.minutes.v1 import (
    GetMinuteRequest,
    GetMinuteStatisticsRequest,
    GetMinuteTranscriptRequest,
)

from ._client import get_client, make_option
from ._scopes import InsufficientScopeError, MODULE_SCOPES


def get_minute(token: str, minute_token: str) -> object:
    client = get_client()
    request = (
        GetMinuteRequest.builder()
        .minute_token(minute_token)
        .user_id_type("open_id")
        .build()
    )
    response = client.minutes.v1.minute.get(request, make_option(token))
    if not response.success():
        if response.code == 99991679:
            raise InsufficientScopeError(MODULE_SCOPES.get("minutes", []), module="minutes")
        raise RuntimeError(
            f"获取妙记失败: code={response.code}, msg={response.msg}"
        )
    return response.data.minute


def get_transcript(
    token: str,
    minute_token: str,
    *,
    need_speaker: bool = True,
    need_timestamp: bool = True,
) -> str:
    client = get_client()
    request = (
        GetMinuteTranscriptRequest.builder()
        .minute_token(minute_token)
        .need_speaker(need_speaker)
        .need_timestamp(need_timestamp)
        .build()
    )
    response = client.minutes.v1.minute_transcript.get(request, make_option(token))
    if not response.success():
        if response.code == 99991679:
            raise InsufficientScopeError(MODULE_SCOPES.get("minutes", []), module="minutes")
        raise RuntimeError(
            f"获取妙记转写失败: code={response.code}, msg={response.msg}"
        )
    return response.file.read().decode("utf-8") if response.file else ""


def get_statistics(token: str, minute_token: str) -> object:
    client = get_client()
    request = (
        GetMinuteStatisticsRequest.builder()
        .minute_token(minute_token)
        .user_id_type("open_id")
        .build()
    )
    response = client.minutes.v1.minute_statistics.get(request, make_option(token))
    if not response.success():
        if response.code == 99991679:
            raise InsufficientScopeError(MODULE_SCOPES.get("minutes", []), module="minutes")
        raise RuntimeError(
            f"获取妙记统计失败: code={response.code}, msg={response.msg}"
        )
    return response.data
