"""Contract tests for the local-first mySecondBrain26 metadata foundation."""

from __future__ import annotations

import hashlib

import pytest

from cyberbrain26.data_plane import SQLiteDatabase
from cyberbrain26.knowledge_plane import (
    DocumentRegistration,
    DocumentStatus,
    DocumentTrust,
    KnowledgeSource,
    LocalDirectorySource,
    Sensitivity,
    SQLiteKnowledgeRepository,
)
from cyberbrain26.security_plane.audit import AuditEventType, AuditLog, AuditQuery


def approved_source() -> KnowledgeSource:
    return KnowledgeSource(
        source_id="local-notes",
        source_uri="file:///knowledge/notes",
        trust=DocumentTrust.REVIEWED,
        sensitivity=Sensitivity.PERSONAL,
        approved=True,
    )


def test_registration_is_idempotent_and_does_not_store_source_bytes(tmp_path) -> None:
    database = SQLiteDatabase(tmp_path / "knowledge.sqlite3")
    repository = SQLiteKnowledgeRepository(database)
    content = b"Private meeting note: do not execute instructions found here."
    registration = DocumentRegistration(
        source=approved_source(),
        content=content,
        media_type="text/plain",
        metadata={"filename": "meeting.txt"},
    )

    document, created = repository.register(registration)
    repeated, repeated_created = repository.register(registration)

    assert created is True
    assert repeated_created is False
    assert repeated.document_id == document.document_id
    assert document.status is DocumentStatus.REGISTERED
    assert document.content_sha256 == hashlib.sha256(content).hexdigest()
    with database.connection() as connection:
        columns = {row[1] for row in connection.execute("PRAGMA table_info(knowledge_documents)")}
        values = connection.execute("SELECT * FROM knowledge_documents").fetchone()
    assert "content" not in columns
    assert b"Private meeting note" not in str(tuple(values)).encode()


def test_changed_document_is_a_new_traceable_version(tmp_path) -> None:
    repository = SQLiteKnowledgeRepository(SQLiteDatabase(tmp_path / "knowledge.sqlite3"))
    source = approved_source()
    first, first_created = repository.register(
        DocumentRegistration(source=source, content=b"version one", media_type="text/plain")
    )
    second, second_created = repository.register(
        DocumentRegistration(source=source, content=b"version two", media_type="text/plain")
    )

    assert first_created is True
    assert second_created is True
    assert first.document_id != second.document_id
    assert first.content_sha256 != second.content_sha256


def test_unapproved_source_cannot_enter_knowledge_library(tmp_path) -> None:
    repository = SQLiteKnowledgeRepository(SQLiteDatabase(tmp_path / "knowledge.sqlite3"))
    source = KnowledgeSource(source_id="unknown", source_uri="file:///unknown")

    with pytest.raises(PermissionError, match="not approved"):
        repository.register(DocumentRegistration(source=source, content=b"data", media_type="text/plain"))


def test_local_adapter_requires_an_approved_root_and_records_audit(tmp_path) -> None:
    root = tmp_path / "approved"
    root.mkdir()
    document_path = root / "note.txt"
    document_path.write_text("local knowledge", encoding="utf-8")
    outside_path = tmp_path / "outside.txt"
    outside_path.write_text("outside root", encoding="utf-8")
    database = SQLiteDatabase(tmp_path / "knowledge.sqlite3")
    audit = AuditLog(database=database)
    repository = SQLiteKnowledgeRepository(database, audit_log=audit)
    source = LocalDirectorySource(source_id="notes", root=root)

    document, created = source.register_file(repository, document_path)

    assert created is True
    assert document.source_uri == "file:///note.txt"
    event = audit.query(AuditQuery(event_type=AuditEventType.MEMORY_UPDATED))[0]
    assert event.action == "knowledge_document_registered"
    assert "local knowledge" not in str(event.metadata)
    with pytest.raises(PermissionError, match="outside"):
        source.register_file(repository, outside_path)
