import json
import hashlib
import threading
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import pytest

from project_brain.graph.generation import GenerationRepository
from project_brain.graph.json_store import JsonStore
from project_brain.query.index import KeywordIndex


def test_publish_and_resolve_current_generation(tmp_path):
    repo = GenerationRepository(tmp_path / "graph")

    published = repo.publish(
        lambda path: (path / "nodes.json").write_text('{"n": 1}', encoding="utf-8"),
        metadata={"node_count": 1},
    )

    assert repo.current_path() == published
    assert repo.validate(published)
    manifest = json.loads((published / "manifest.json").read_text(encoding="utf-8"))
    assert manifest["metadata"]["node_count"] == 1


def test_failed_publish_keeps_previous_generation(tmp_path):
    repo = GenerationRepository(tmp_path / "graph")
    first = repo.publish(
        lambda path: (path / "nodes.json").write_text("first", encoding="utf-8")
    )

    def fail(path):
        (path / "nodes.json").write_text("partial", encoding="utf-8")
        raise RuntimeError("boom")

    with pytest.raises(RuntimeError):
        repo.publish(fail)

    assert repo.current_path() == first
    assert (first / "nodes.json").read_text(encoding="utf-8") == "first"


def test_current_write_failure_removes_unpublished_generation(tmp_path, monkeypatch):
    repo = GenerationRepository(tmp_path / "graph")
    first = repo.publish(
        lambda path: (path / "nodes.json").write_text("first", encoding="utf-8")
    )

    def fail_current_write(path, content):
        raise OSError("injected CURRENT failure")

    monkeypatch.setattr(repo, "_atomic_write_text", fail_current_write)

    with pytest.raises(OSError, match="injected CURRENT failure"):
        repo.publish(
            lambda path: (path / "nodes.json").write_text(
                "unpublished", encoding="utf-8"
            )
        )

    assert repo.current_path() == first
    assert list(repo.generations.iterdir()) == [first]


def test_cleanup_failure_after_current_switch_is_only_a_warning(
    tmp_path, monkeypatch, caplog
):
    repo = GenerationRepository(tmp_path / "graph")
    first = repo.publish(
        lambda path: (path / "nodes.json").write_text("first", encoding="utf-8")
    )

    def fail_cleanup(*, exclude):
        raise OSError("injected cleanup failure")

    monkeypatch.setattr(repo, "_cleanup_old_generations", fail_cleanup)
    published = repo.publish(
        lambda path: (path / "nodes.json").write_text("second", encoding="utf-8")
    )

    assert published != first
    assert repo.current_path() == published
    assert (published / "nodes.json").read_text(encoding="utf-8") == "second"
    assert "old-generation cleanup failed" in caplog.text


def test_corrupt_current_falls_back_to_previous_complete_generation(tmp_path):
    repo = GenerationRepository(tmp_path / "graph", keep=3)
    first = repo.publish(
        lambda path: (path / "nodes.json").write_text("first", encoding="utf-8")
    )
    second = repo.publish(
        lambda path: (path / "nodes.json").write_text("second", encoding="utf-8")
    )
    (second / "nodes.json").write_text("corrupt", encoding="utf-8")

    assert repo.current_path() == first


def test_invalid_utf8_current_falls_back_to_latest_complete_generation(tmp_path):
    repo = GenerationRepository(tmp_path / "graph", keep=3)
    repo.publish(
        lambda path: (path / "nodes.json").write_text("first", encoding="utf-8")
    )
    latest = repo.publish(
        lambda path: (path / "nodes.json").write_text("latest", encoding="utf-8")
    )
    repo.current_file.write_bytes(b"\xff\xfe\xfa")

    assert repo.current_path() == latest


@pytest.mark.parametrize(
    "invalid_manifest",
    [
        [],
        {"format_version": 1, "artifacts": None},
        {"format_version": 1, "artifacts": []},
        {"format_version": 1, "artifacts": {}},
        {"format_version": 1, "artifacts": {"nodes.json": None}},
        {
            "format_version": 1,
            "artifacts": {"nodes.json": {"size": "1", "sha256": []}},
        },
    ],
)
def test_invalid_manifest_shape_falls_back_to_previous_generation(
    tmp_path, invalid_manifest
):
    repo = GenerationRepository(tmp_path / "graph", keep=3)
    previous = repo.publish(
        lambda path: (path / "nodes.json").write_text("previous", encoding="utf-8")
    )
    latest = repo.publish(
        lambda path: (path / "nodes.json").write_text("latest", encoding="utf-8")
    )
    if isinstance(invalid_manifest, dict):
        invalid_manifest["generation"] = latest.name
    (latest / "manifest.json").write_text(
        json.dumps(invalid_manifest), encoding="utf-8"
    )

    assert repo.current_path() == previous


def test_invalid_utf8_manifest_falls_back_to_previous_generation(tmp_path):
    repo = GenerationRepository(tmp_path / "graph", keep=3)
    previous = repo.publish(
        lambda path: (path / "nodes.json").write_text("previous", encoding="utf-8")
    )
    latest = repo.publish(
        lambda path: (path / "nodes.json").write_text("latest", encoding="utf-8")
    )
    (latest / "manifest.json").write_bytes(b"\xff\xfe\xfa")

    assert repo.current_path() == previous


def test_manifest_artifact_cannot_escape_generation_directory(tmp_path):
    repo = GenerationRepository(tmp_path / "graph", keep=3)
    previous = repo.publish(
        lambda path: (path / "nodes.json").write_text("previous", encoding="utf-8")
    )
    latest = repo.publish(
        lambda path: (path / "nodes.json").write_text("latest", encoding="utf-8")
    )
    outside = repo.generations / "outside.bin"
    outside.write_bytes(b"outside")
    manifest = json.loads((latest / "manifest.json").read_text(encoding="utf-8"))
    manifest["artifacts"] = {
        "../outside.bin": {
            "size": outside.stat().st_size,
            "sha256": hashlib.sha256(outside.read_bytes()).hexdigest(),
        }
    }
    (latest / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")

    assert repo.current_path() == previous


def test_corrupt_generation_does_not_consume_retention_slot(tmp_path):
    repo = GenerationRepository(tmp_path / "graph", keep=2)
    first = repo.publish(
        lambda path: (path / "nodes.json").write_text("first", encoding="utf-8")
    )
    corrupt = repo.publish(
        lambda path: (path / "nodes.json").write_text("corrupt", encoding="utf-8")
    )
    (corrupt / "nodes.json").write_text("damaged", encoding="utf-8")

    latest = repo.publish(
        lambda path: (path / "nodes.json").write_text("latest", encoding="utf-8")
    )

    assert repo.current_path() == latest
    assert first.is_dir()
    assert not corrupt.exists()


def test_without_generation_uses_legacy_root(tmp_path):
    root = tmp_path / "graph"
    root.mkdir()
    (root / "nodes.json").write_text("{}", encoding="utf-8")

    assert GenerationRepository(root).current_path() == root


def test_publish_graph_state_contains_graph_and_keyword_index(tmp_path):
    class SemanticStub:
        def save(self, path):
            semantic_dir = Path(path) / "semantic_normal"
            semantic_dir.mkdir(parents=True)
            (semantic_dir / "semantic_ids.json").write_text("{}", encoding="utf-8")

    root = tmp_path / "graph"
    store = JsonStore(root)
    store.add_node({"id": "doc_1", "type": "document", "title": "Current"})
    keyword = KeywordIndex()
    keyword.add("doc_1", "current generation")

    published = GenerationRepository(root).publish_graph_state(
        store, keyword, SemanticStub()
    )

    assert (published / "nodes.json").is_file()
    assert (published / "edges.json").is_file()
    assert (published / "keyword_index.json").is_file()
    assert (published / "semantic_normal" / "semantic_ids.json").is_file()
    loaded = KeywordIndex()
    assert loaded.load(published)
    assert loaded.search("current")[0][0] == "doc_1"


def test_incomplete_graph_state_does_not_advance_current(tmp_path):
    class BrokenStore:
        def save(self, path):
            return None

    root = tmp_path / "graph"
    repo = GenerationRepository(root)
    first = repo.publish(
        lambda path: (path / "nodes.json").write_text("first", encoding="utf-8")
    )

    with pytest.raises(RuntimeError, match="Incomplete JSON graph generation"):
        repo.publish_graph_state(BrokenStore(), KeywordIndex())

    assert repo.current_path() == first


def test_concurrent_publishers_serialize_current_pointer(tmp_path):
    root = tmp_path / "graph"
    barrier = threading.Barrier(2)

    def publish(label):
        repo = GenerationRepository(root)

        def write(path):
            (path / "nodes.json").write_text(label, encoding="utf-8")
            barrier.wait(timeout=5)

        return repo.publish(write)

    with ThreadPoolExecutor(max_workers=2) as pool:
        published = list(pool.map(publish, ("one", "two")))

    repo = GenerationRepository(root)
    assert all(repo.validate(path) for path in published)
    assert repo.current_path() in published