from __future__ import annotations

import re
from dataclasses import dataclass
from pathlib import Path

from youtube_cli_agent.models import FileCheckResult


@dataclass(slots=True)
class DuplicateCheckerTool:
    min_transcript_chars: int = 80

    def run(self, path: Path) -> FileCheckResult:
        if not path.exists():
            return FileCheckResult(
                path=path,
                exists=False,
                is_valid=False,
                has_transcript=False,
                is_corrupt=False,
                reason="File does not exist.",
            )

        if not path.is_file():
            return FileCheckResult(
                path=path,
                exists=True,
                is_valid=False,
                has_transcript=False,
                is_corrupt=True,
                reason="Target path exists but is not a file.",
            )

        try:
            content = path.read_text(encoding="utf-8")
        except Exception:
            return FileCheckResult(
                path=path,
                exists=True,
                is_valid=False,
                has_transcript=False,
                is_corrupt=True,
                reason="File cannot be read as UTF-8 markdown.",
            )

        checks = {
            "title": re.search(r"^# .+", content, flags=re.MULTILINE) is not None,
            "channel": "- Channel:" in content,
            "url": "- Video URL:" in content,
            "publish_date": "- Publish Date:" in content,
            "duration": "- Duration:" in content,
            "description": "## Description" in content,
            "transcript": "## Transcript" in content,
            "source": "- Transcript Source:" in content,
            "generated_at": "- Generated At (UTC):" in content,
        }

        missing_sections = [name for name, passed in checks.items() if not passed]
        if missing_sections:
            return FileCheckResult(
                path=path,
                exists=True,
                is_valid=False,
                has_transcript=False,
                is_corrupt=True,
                reason=f"Missing required sections: {', '.join(sorted(missing_sections))}",
            )

        transcript = self._extract_transcript(content)
        normalized = " ".join(transcript.split())
        has_transcript = len(normalized) >= self.min_transcript_chars

        if not has_transcript:
            return FileCheckResult(
                path=path,
                exists=True,
                is_valid=False,
                has_transcript=False,
                is_corrupt=True,
                reason="Transcript section exists but is empty or too short.",
            )

        return FileCheckResult(
            path=path,
            exists=True,
            is_valid=True,
            has_transcript=True,
            is_corrupt=False,
            reason="Transcript file exists and passed integrity checks.",
        )

    @staticmethod
    def _extract_transcript(content: str) -> str:
        marker = "## Transcript"
        source_marker = "## Metadata"
        if marker not in content:
            return ""
        start = content.index(marker) + len(marker)
        if source_marker in content[start:]:
            end = content.index(source_marker, start)
            return content[start:end]
        return content[start:]
