from pathlib import Path

from cyberbrain26.product.shared_root import (
    claim_batch,
    ensure_shared_root,
    is_rclone_configured,
    is_sensitive_path,
    list_mountpoints,
    manifest_path,
    manifest_write,
    resolve_shared_root,
)


def test_resolve_shared_root_explicit(tmp_path: Path):
    root = resolve_shared_root(tmp_path / "shared")
    assert root == (tmp_path / "shared").resolve()


def test_resolve_shared_root_env(tmp_path: Path, monkeypatch):
    monkeypatch.setenv("UNIFIED_INGEST_ROOT", str(tmp_path / "envroot"))
    root = resolve_shared_root()
    assert root == (tmp_path / "envroot").resolve()


def test_ensure_shared_root_creates_subdirs(tmp_path: Path):
    root = ensure_shared_root(tmp_path / "shared")
    for sub in ("inbox", "processing", "sorted", "duplicates", "index", "tasks", "manifest"):
        assert (root / sub).is_dir()
    assert (root / "manifest" / "ingest-manifest.jsonl").is_file()


def test_is_sensitive_path():
    assert is_sensitive_path("/home/u/.ssh/id_rsa")
    assert is_sensitive_path("credentials.json")
    assert is_sensitive_path("foo/secret.txt")
    assert is_sensitive_path("key.pem")
    assert not is_sensitive_path("/tmp/notes.txt")


def test_manifest_write_and_path(tmp_path: Path):
    root = ensure_shared_root(tmp_path / "shared")
    manifest_write({"a": 1}, shared_root=root)
    mp = manifest_path(root)
    assert mp.exists()
    assert "a" in mp.read_text()


def test_claim_batch_moves_files(tmp_path: Path):
    root = ensure_shared_root(tmp_path / "shared")
    inbox = root / "inbox"
    (inbox / "note.txt").write_text("hello")
    (inbox / "secret.key").write_text("secret")
    result = claim_batch(shared_root=root, limit=10)
    assert result["count"] == 1
    assert len(result["claimed"]) == 1
    assert len(result["skipped"]) == 1
    assert not (inbox / "note.txt").exists()
    batch_dir = root / "processing" / result["batch_id"]
    assert (batch_dir / "note.txt").exists()


def test_detect_syncthing_folders_empty(tmp_path: Path, monkeypatch):
    monkeypatch.setattr("cyberbrain26.product.shared_root.SYNCTHING_CONFIG", str(tmp_path / "no.xml"))
    from cyberbrain26.product.shared_root import detect_syncthing_folders

    assert detect_syncthing_folders() == []


def test_is_rclone_configured_false(tmp_path: Path, monkeypatch):
    monkeypatch.setattr("cyberbrain26.product.shared_root.RCLONE_CONFIG", str(tmp_path / "no.conf"))
    assert is_rclone_configured() is False


def test_list_mountpoints_returns_list():
    assert isinstance(list_mountpoints(), list)
