"""Teams transcript plugin — manual paste / file drop of Teams transcripts."""

from __future__ import annotations

import os
import re


def _parse_teams_speakers(text: str) -> list[str]:
    """Extract unique speaker names from Teams format 'Name HH:MM:SS'."""
    # Pattern: "Speaker Name 0:01:23" or "Name 1:23:45"
    pattern = r"^([^0-9\n:]+?)\s*\d{1,2}:\d{2}:\d{2}"
    matches = re.findall(pattern, text, re.MULTILINE)
    seen: set[str] = set()
    speakers: list[str] = []
    for m in matches:
        name = m.strip()
        if name and name not in seen:
            seen.add(name)
            speakers.append(name)
    return speakers


class TeamsTranscriptAdapter:
    """TranscriptProvider for manual Teams transcript input (paste or file)."""

    def __init__(self) -> None:
        """No configuration needed — manual input only."""

    async def fetch_transcript(self, recording_id: str) -> dict:
        """Fetch transcript: recording_id is a file path or raw transcript text."""
        if os.path.isfile(recording_id):
            with open(recording_id, encoding="utf-8", errors="replace") as f:
                content = f.read()
        else:
            content = recording_id

        speakers = _parse_teams_speakers(content)
        return {
            "text": content,
            "speakers": speakers,
            "metadata": {"source": "teams_manual"},
        }

    async def list_recordings(
        self,
        start_date: str | None = None,
        end_date: str | None = None,
    ) -> list[dict]:
        """Manual input has no recordings to list."""
        return []


def register() -> None:
    """Register the Teams transcript plugin with the loader."""
    from vastian.loader import register as loader_register

    loader_register("teams_transcript", TeamsTranscriptAdapter)
