# This is free software for the public good of a permacomputer hosted at
# permacomputer.com, an always-on computer by the people, for the people.
# One which is durable, easy to repair, & distributed like tap water
# for machine learning intelligence.
#
# The permacomputer is community-owned infrastructure optimized around
# four values:
#
#   TRUTH      First principles, math & science, open source code freely distributed
#   FREEDOM    Voluntary partnerships, freedom from tyranny & corporate control
#   HARMONY    Minimal waste, self-renewing systems with diverse thriving connections
#   LOVE       Be yourself without hurting others, cooperation through natural law
#
# This software contributes to that vision by archiving the web, preserving digital knowledge before it disappears.
# Code is seeds to sprout on any abandoned technology.

"""Tests for the optional arborist provenance sink.

Disabled-path tests run anywhere. The enabled-path test skips when
arborist is not installed (it is an opt-in dependency).
"""

import pytest

from neopig.arborist_sink import ArboristSink


def test_disabled_by_default(monkeypatch):
    """No flag -> sink off, regardless of whether arborist is installed."""
    monkeypatch.delenv("NEOPIG_ARBORIST_ENABLED", raising=False)
    sink = ArboristSink()
    assert sink.enabled is False


@pytest.mark.asyncio
async def test_ingest_page_is_noop_when_disabled(tmp_path, monkeypatch):
    monkeypatch.delenv("NEOPIG_ARBORIST_ENABLED", raising=False)
    db = tmp_path / "arborist.db"
    sink = ArboristSink(db_path=str(db), enabled=False)
    result = await sink.ingest_page("https://x.com/a", "Title", "body text")
    assert result is False
    assert not db.exists(), "disabled sink must not create a store"


def test_flag_without_arborist_stays_disabled(monkeypatch):
    """Flag on but arborist missing -> still disabled (no crash)."""
    monkeypatch.setattr("neopig.arborist_sink._ARBORIST_AVAILABLE", False)
    sink = ArboristSink(enabled=True)
    assert sink.available is False
    assert sink.enabled is False


def test_page_to_document_mapping():
    """Mapping is pure and available even when the sink is disabled,
    as long as arborist's types import. Skip if arborist absent."""
    pytest.importorskip("arborist")
    sink = ArboristSink(enabled=False)
    doc = sink._page_to_document(
        "https://x.com/post",
        "A Post",
        "the page prose",
        path="/post",
        crawl_job_id=7,
        media_uris=["https://x.com/img.jpg"],
    )
    assert doc.uri == "https://x.com/post"
    assert doc.source_type == "neopig_html"
    assert doc.title == "A Post"
    assert doc.extra["crawl_job_id"] == 7
    assert doc.extra["md5_uri_hash"]  # provenance carried along
    assert any(e.dst_uri == "https://x.com/img.jpg" for e in doc.edges)


@pytest.mark.asyncio
async def test_enabled_path_ingests_into_arborist(tmp_path):
    """End-to-end: flag on + arborist installed -> page lands in the store
    and is content-deduped. Skips when arborist is not installed."""
    pytest.importorskip("arborist")
    from arborist.embed import open_store

    db = tmp_path / "arborist.db"
    sink = ArboristSink(db_path=str(db), enabled=True)
    assert sink.enabled is True

    ok = await sink.ingest_page(
        "https://x.com/post", "A Post", "the quick brown fox", path="/post", crawl_job_id=1
    )
    assert ok is True
    assert db.exists()

    conn = open_store(str(db))
    try:
        n = conn.execute("SELECT COUNT(*) FROM documents").fetchone()[0]
        assert n == 1
        # Re-ingest identical content -> idempotent, still one doc.
        await sink.ingest_page("https://x.com/post", "A Post", "the quick brown fox", path="/post")
        n2 = conn.execute("SELECT COUNT(*) FROM documents").fetchone()[0]
        assert n2 == 1
    finally:
        conn.close()
