import re
from collections.abc import Generator
from pathlib import Path

from pydantic import BaseModel


class CleanCCSvc(BaseModel):
    @classmethod
    def clean_vtt_line(cls, line):
        """
        Clean a single line of VTT text by removing timestamps and HTML tags.

        Args:
            line (str): Single line from VTT file

        Returns:
            str: Cleaned line or None if line should be skipped
        """
        # Skip empty lines
        if not line.strip():
            return None
        # Skip WEBVTT header
        if line.strip().startswith("WEBVTT"):
            return None

        # Skip timestamp lines (e.g., "00:00:00.000 --> 00:00:02.000")
        if re.match(
            r"\d{2}:\d{2}:\d{2}\.\d{3}\s+-{2}>\s+\d{2}:\d{2}:\d{2}\.\d{3}", line
        ):
            return None

        # Skip numeric identifiers
        if line.strip().isdigit():
            return None

        # Remove HTML-style tags
        line = re.sub(r"<[^>]+>", "", line)

        # Remove multiple spaces
        line = " ".join(line.split())

        return line.strip()

    @classmethod
    def process_vtt_file(cls, file_path: Path):
        seen_lines = set()

        with file_path.open("r", encoding="utf-8") as f:
            for line in f:
                cleaned = cls.clean_vtt_line(line)
                if line not in seen_lines:
                    seen_lines.add(line)
                    yield cleaned

    def run(self, cc_file_path: Path) -> Generator[str, None, None]:
        return self.process_vtt_file(cc_file_path)
