"""Local Vault notes provider adapter."""

from __future__ import annotations

from pathlib import Path
from typing import Any

from sqlalchemy.orm import Session

from app.services import vault
from app.services.integrations.errors import ProviderNotConfiguredError
from app.services.integrations.types import NotesHit, ProviderConnectionResult


class VaultLocalNotesProvider:
    """Notes provider backed by local SQLite FTS vault."""

    provider_id = "vault_local"
    display_name = "Vault (Local)"

    def __init__(self, *, paths: list[str]):
        self._paths = [str(item).strip() for item in paths if str(item).strip()]

    def _ensure_enabled(self) -> None:
        if not self._paths:
            raise ProviderNotConfiguredError("Vault local paths are not configured")

    def search(self, *, query: str, limit: int = 5, db: Session | None = None) -> list[NotesHit]:
        self._ensure_enabled()
        if db is None:
            raise ProviderNotConfiguredError("Vault local search requires database session")
        hits = vault.retrieve_relevant_chunks(db=db, query=query, limit=limit, explicit=True)
        result: list[NotesHit] = []
        for item in hits:
            snippet = " ".join(item.snippet.split())
            result.append(
                NotesHit(
                    provider=self.provider_id,
                    id=str(item.chunk_id),
                    title=Path(item.file_path).name,
                    snippet=snippet,
                    source=item.file_path,
                    raw={"rank": item.rank, "overlap": item.overlap},
                ),
            )
        return result

    def create_note(self, *, title: str, content: str, db: Session | None = None) -> str:
        self._ensure_enabled()
        target_dir = Path(self._paths[0]).expanduser()
        target_dir.mkdir(parents=True, exist_ok=True)
        safe_name = "".join(ch if ch.isalnum() or ch in {"-", "_"} else "_" for ch in title.lower()).strip("_")
        if not safe_name:
            safe_name = "note"
        path = target_dir / f"{safe_name}.md"
        path.write_text(f"# {title}\n\n{content}\n", encoding="utf-8")
        return str(path)

    def append_note(self, *, target_id: str, content: str, db: Session | None = None) -> None:
        self._ensure_enabled()
        target_path = Path(target_id).expanduser()
        target_path.parent.mkdir(parents=True, exist_ok=True)
        with target_path.open("a", encoding="utf-8") as file_obj:
            file_obj.write(f"\n\n{content}\n")

    def test_connection(self, db: Session | None = None) -> ProviderConnectionResult:
        if not self._paths:
            return ProviderConnectionResult(ok=False, detail="No vault local paths configured")
        missing = [item for item in self._paths if not Path(item).exists()]
        if missing:
            return ProviderConnectionResult(ok=False, detail=f"Missing path(s): {', '.join(missing)}")
        return ProviderConnectionResult(ok=True, detail=f"{len(self._paths)} path(s) configured")
