"""
tkasrプロジェクトで共有されるデータ型やファイル/音声処理のヘルパー関数を提供します。

音声認識(ASR)関連のアプリケーションで共通して利用されるユーティリティ機能を集約しています。
ファイル操作、FFmpeg/FFprobeの利用、ASR結果のデータ構造などが含まれます。

:doc:`tkasr_usage`
"""
from __future__ import annotations

import json
import subprocess
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Optional


class OptionalDependencyError(RuntimeError):
    """
    オプションのバックエンドまたは機能がインストールされていない場合に発生するエラー。
    """


@dataclass
class Segment:
    """
    音声認識結果の1セグメントを表すデータクラス。

    :param start: セグメントの開始時間（秒）。
    :param end: セグメントの終了時間（秒）。
    :param text: セグメントのテキスト。
    """
    start: Optional[float]
    end: Optional[float]
    text: str


@dataclass
class ASRResult:
    """
    音声認識全体の単一結果を表すデータクラス。

    :param text: 音声認識された完全なテキスト。
    :param segments: テキストを時間情報付きのセグメントに分割したリスト。
    :param language: 認識された言語コード（例: "en", "ja"）。
    :param metadata: その他のメタデータ。
    """
    text: str
    segments: list[Segment] = field(default_factory=list)
    language: Optional[str] = None
    metadata: dict[str, Any] = field(default_factory=dict)


def run_command(command: list[str]) -> str:
    """
    外部コマンドを実行し、その標準出力を取得します。

    `subprocess.run` を使用してコマンドを実行し、エラーが発生した場合は適切な `RuntimeError` を発生させます。
    コマンドが見つからない場合や、コマンドがエラー終了した場合に詳細なエラーメッセージを提供します。

    :param command: 実行するコマンドとその引数を表す文字列のリスト。
    :type command: list[str]
    :returns: コマンドの標準出力。
    :rtype: str
    :raises RuntimeError: コマンドが見つからない場合、またはコマンドがエラー終了した場合。
    """
    try:
        result = subprocess.run(command, check=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    except FileNotFoundError as exc:
        raise RuntimeError(f"'{command[0]}' が見つかりません。FFmpeg を PATH に追加するか --ffmpeg-dir を指定してください。") from exc
    except subprocess.CalledProcessError as exc:
        raise RuntimeError(exc.stderr.strip() or exc.stdout.strip() or f"コマンドが失敗しました: {command}") from exc
    return result.stdout.strip()


def ffmpeg_commands(directory: Optional[Path]) -> tuple[str, str]:
    """
    FFmpegとFFprobeの実行可能ファイルのパスを決定します。

    指定されたディレクトリが存在しない場合、またはディレクトリ内に`ffmpeg`と`ffprobe`が見つからない場合はエラーとなります。
    Windows環境では実行ファイルに`.exe`拡張子が付与されます。
    `directory`が`None`の場合、システムPATHから`ffmpeg`と`ffprobe`を検索します。

    :param directory: FFmpegバイナリが格納されているディレクトリのパス。`None` の場合はシステムのPATHから検索されます。
    :type directory: Optional[Path]
    :returns: FFmpegとFFprobeのフルパスのタプル。
    :rtype: tuple[str, str]
    :raises RuntimeError: 指定されたディレクトリに `ffmpeg` または `ffprobe` が見つからない場合。
    """
    if directory is None:
        return "ffmpeg", "ffprobe"
    suffix = ".exe" if __import__("sys").platform == "win32" else ""
    directory = directory.expanduser().resolve()
    ffmpeg, ffprobe = directory / f"ffmpeg{suffix}", directory / f"ffprobe{suffix}"
    if not ffmpeg.is_file() or not ffprobe.is_file():
        raise RuntimeError("--ffmpeg-dir には ffmpeg と ffprobe がある bin フォルダを指定してください。")
    return str(ffmpeg), str(ffprobe)


def audio_duration(source: Path, ffprobe: str) -> float:
    """
    音声ファイルの長さを取得します。

    `ffprobe` コマンドを使用して音声ファイルの `duration` 情報を抽出し、
    秒単位の浮動小数点数として返します。

    :param source: 音声ファイルへのパス。
    :type source: Path
    :param ffprobe: `ffprobe` 実行ファイルのフルパス。
    :type ffprobe: str
    :returns: 音声ファイルの長さ（秒）。
    :rtype: float
    :raises RuntimeError: 音声ファイルの長さを取得できなかった場合。
    """
    try:
        return float(run_command([ffprobe, "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", str(source)]))
    except ValueError as exc:
        raise RuntimeError("音声長を取得できませんでした。") from exc


def extract_wav(source: Path, start: float, length: float, destination: Path, ffmpeg: str) -> None:
    """
    音声ファイルから指定された範囲をWAV形式で抽出します。

    `ffmpeg` コマンドを使用して、元の音声ファイルから指定された開始時間と長さの部分を
    モノラル、16kHzサンプリングレート、PCM_s16le形式のWAVファイルとして出力します。

    :param source: 元の音声ファイルへのパス。
    :type source: Path
    :param start: 抽出開始時間（秒）。
    :type start: float
    :param length: 抽出する長さ（秒）。
    :type length: float
    :param destination: 抽出されたWAVファイルの出力パス。
    :type destination: Path
    :param ffmpeg: `ffmpeg` 実行ファイルのフルパス。
    :type ffmpeg: str
    :returns: None
    :rtype: None
    """
    run_command([ffmpeg, "-hide_banner", "-loglevel", "error", "-y", "-ss", f"{start:.3f}", "-t", f"{length:.3f}", "-i", str(source), "-vn", "-map", "0:a:0", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", str(destination)])


def hms(seconds: Optional[float]) -> str:
    """
    秒数を `HH:MM:SS.ss` 形式の文字列に変換します。

    `None` が指定された場合は `??:??:??.??` を返します。
    負の秒数は0として扱われます。

    :param seconds: 変換する秒数。
    :type seconds: Optional[float]
    :returns: フォーマットされた時間文字列。
    :rtype: str
    """
    if seconds is None:
        return "??:??:??.??"
    seconds = max(0.0, seconds)
    return f"{int(seconds // 3600):02d}:{int(seconds % 3600 // 60):02d}:{seconds % 60:05.2f}"


def save_json(path: Path, value: dict[str, Any]) -> None:
    """
    指定されたパスに辞書をJSON形式で保存します。

    一時ファイルに書き込んだ後、元のファイルを置き換えることで、
    ファイル破損のリスクを低減するアトミックな保存を試みます。
    非ASCII文字も正しく保存されます。

    :param path: 保存先のファイルパス。
    :type path: Path
    :param value: 保存する辞書データ。
    :type value: dict[str, Any]
    :returns: None
    :rtype: None
    """
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding="utf-8")
    temporary.replace(path)


def write_outputs(output: Path, result: ASRResult, report: dict[str, Any], corrected: Optional[str]) -> None:
    """
    音声認識結果とレポートを複数のファイル形式で出力します。

    以下のファイルを出力します:
    - 時刻付きテキストファイル (例: ``{output_stem}-time.txt``)
    - プレーンテキストファイル (例: ``{output_stem}.txt``)
    - JSON形式のレポートファイル (例: ``{output_stem}-info.json``)
    `corrected` が提供されている場合、校正済みテキストファイルも出力されます (例: ``{output_stem}.corrected.txt``)。

    :param output: 出力ファイル名のベースパス（拡張子なし）。
                   例: `Path("output/audio")` と指定すると、`output/audio-time.txt` などが生成されます。
    :type output: Path
    :param result: 音声認識の結果データ。
    :type result: ASRResult
    :param report: その他のレポート情報。
    :type report: dict[str, Any]
    :param corrected: 校正済みのテキスト。提供されている場合のみ出力されます。
    :type corrected: Optional[str]
    :returns: None
    :rtype: None
    """
    time_file = output.with_name(output.stem + "-time.txt")
    plain_file = output.with_suffix(".txt")
    info_file = output.with_name(output.stem + "-info.json")
    with time_file.open("w", encoding="utf-8") as handle:
        for segment in result.segments:
            handle.write(f"[{hms(segment.start)} - {hms(segment.end)}] {segment.text}\n")
        if not result.segments:
            handle.write(result.text + "\n")
    plain_file.write_text(result.text + ("\n" if result.text else ""), encoding="utf-8")
    info_file.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(f"時刻付き: {time_file}\nASR原文 : {plain_file}\n情報     : {info_file}")
    if corrected is not None:
        corrected_file = plain_file.with_name(plain_file.stem + ".corrected.txt")
        corrected_file.write_text(corrected + "\n", encoding="utf-8")
        print(f"校正済み: {corrected_file}")
