import io
import json
import tarfile
import zipfile

from pallet.data.inventory import inventory, resolve_pending


def test_inventory_keeps_unmatched_and_verifies_zip_crc(tmp_path):
    root = tmp_path / "data"
    root.mkdir()
    (root / "untimed.pcd").write_bytes(
        b"FIELDS x y z\nSIZE 4 4 4\nTYPE F F F\nWIDTH 1\nHEIGHT 1\nPOINTS 1\nDATA ascii\n1 2 3\n")
    (root / "empty.pcd").touch()
    (root / "same.txt").write_bytes(b"equal")
    (root / "wrong.txt").write_bytes(b"wrong")
    with zipfile.ZipFile(root / "items.zip", "w") as archive:
        archive.writestr("same.txt", b"equal")
        archive.writestr("wrong.txt", b"other")
        archive.writestr("../escape.txt", b"bad")
    with tarfile.open(root / "items.tar.gz", "w:gz") as archive:
        archive.add(root / "same.txt", arcname="same.txt")
    output = tmp_path / "out"
    summary = inventory(root, output)
    rows = [json.loads(line) for line in (output / "items.jsonl").read_text().splitlines()]
    members = {row["member"]: row for row in rows if row["kind"] == "archive_member" and row["archive"] == "items.zip"}
    assert members["same.txt"]["classification"] == "duplicate"
    assert members["wrong.txt"]["reason"] == "content_mismatch"
    assert members["../escape.txt"]["reason"] == "unsafe_member_path"
    assert any(row["archive"] == "items.tar.gz" and row["classification"] == "duplicate" for row in rows if row["kind"] == "archive_member")
    assert summary["files"] == 6
    assert summary["archive_member_rows"] == 4
    assert summary["non_timestamp_pcd_candidates"] == ["untimed.pcd"]
    assert next(row for row in rows if row.get("path") == "empty.pcd")["classification"] == "damaged"


def test_invalid_untimed_pcd_is_damaged(tmp_path):
    root = tmp_path / "data"
    root.mkdir()
    (root / "bad.pcd").write_bytes(b"not a PCD")
    result = inventory(root, tmp_path / "out")
    assert result["non_timestamp_pcd_candidates"] == []
    assert result["reasons"]["incomplete_pcd_header"] == 1


def test_resolve_unique_and_cross_path_duplicate_members(tmp_path, monkeypatch):
    monkeypatch.setattr("pallet.data.inventory.FREE_FLOOR", 0)
    monkeypatch.setattr("pallet.data.inventory.shutil.disk_usage", lambda _: type("Usage", (), {"free": 100 * 1024**3})())
    root = tmp_path / "data"
    root.mkdir()
    (root / "copied.pcd").write_bytes(b"same sensor")
    with zipfile.ZipFile(root / "batch.zip", "w") as archive:
        archive.writestr("other/same.pcd", b"same sensor")
        archive.writestr("other/new.pcd", b"unique sensor")
        archive.writestr("other/empty.jpg", b"")
        archive.writestr("notes.txt", b"ancillary")
    output = tmp_path / "out"
    inventory(root, output)
    summary = resolve_pending(root, output)
    assert summary["unique_archived_sensors"] == 1
    records = [json.loads(line) for line in (output / "unique_sensor_records.jsonl").read_text().splitlines()]
    assert len(records) == 1
    assert records[0]["original_name"] == "new.pcd"
    assert (output / "extracted" / (records[0]["sha256"] + ".pcd")).read_bytes() == b"unique sensor"
    members = {row["member"]: row for row in map(json.loads, (output / "items.jsonl").read_text().splitlines()) if row["kind"] == "archive_member"}
    assert members["other/same.pcd"]["reason"] == "same_sha256_as_disk_file"
    assert members["other/empty.jpg"]["reason"] == "zero_byte_archive_sensor"
    assert members["notes.txt"]["reason"] == "ancillary_archive_member"


def test_nested_tar_member_is_reconciled(tmp_path, monkeypatch):
    monkeypatch.setattr("pallet.data.inventory.shutil.disk_usage", lambda _: type("Usage", (), {"free": 100 * 1024**3})())
    root = tmp_path / "data"
    root.mkdir()
    (root / "same.pcd").write_bytes(b"nested sensor")
    nested = io.BytesIO()
    with tarfile.open(fileobj=nested, mode="w:gz") as archive:
        info = tarfile.TarInfo("inside/same.pcd")
        info.size = len(b"nested sensor")
        archive.addfile(info, io.BytesIO(b"nested sensor"))
    with zipfile.ZipFile(root / "outer.zip", "w") as outer:
        outer.writestr("inside.tar.gz", nested.getvalue())
    output = tmp_path / "out"
    inventory(root, output)
    summary = resolve_pending(root, output)
    assert summary["unique_archived_sensors"] == 0
    assert any(row.get("archive") == "outer.zip::inside.tar.gz" and row["reason"] == "same_sha256_as_disk_file"
               for row in map(json.loads, (output / "items.jsonl").read_text().splitlines()))
