from __future__ import annotations

"""Filesystem-based ingestor.

This module deals only with local files and does not attempt to parse their
content; it simply loads bytes/text and wraps them into :class:`RawDocument`.
Parsing into a ``DocumentTree`` is handled by the ``parsing`` package.
"""

from pathlib import Path
from typing import Optional

from ..core.models import RawDocument, SourceType
from .base import BaseIngestor, IngestionError


class FileIngestor(BaseIngestor):
    """Ingestor for local files.

    For neuraparse v0.1 we treat all files as UTF-8 encoded text and leave
    format-specific understanding (PDF, HTML, etc.) to the parsing layer.
    """

    def __init__(self, base_dir: Optional[Path] = None) -> None:
        self._base_dir = base_dir or Path.cwd()

    def supports(self, source: str) -> bool:
        path = Path(source)
        if not path.is_absolute():
            path = self._base_dir / path
        return path.is_file()

    def ingest(self, source: str) -> RawDocument:
        path = Path(source)
        if not path.is_absolute():
            path = self._base_dir / path

        if not path.is_file():
            raise IngestionError(f"File not found: {path}")

        text = path.read_text(encoding="utf-8", errors="ignore")

        return RawDocument(
            id=str(path.resolve()),
            source_type=SourceType.FILE,
            content=text,
            metadata={
                "path": str(path),
            },
        )

