import tempfile
import unittest
from pathlib import Path

from gnos.core.add import add_collection, _sort_collection_entries
from gnos.core.store import ObjectStore
from gnos.manifest.codec import load_collection_bytes
from gnos.manifest.schema import CollectionEntry


class TestCollectionOrdering(unittest.TestCase):
    def test_order_by_path_then_doc_id(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            store = ObjectStore(root / ".gnos")
            store.init()

            docs = root / "docs"
            docs.mkdir()
            # Create files in reverse order to ensure sorting is applied.
            (docs / "b.md").write_text("# B\n", encoding="utf-8")
            (docs / "a.md").write_text("# A\n", encoding="utf-8")

            result = add_collection(docs, store)
            blob = store.get(result.collection_id)
            self.assertIsNotNone(blob)
            col = load_collection_bytes(blob)

            paths = [d.path for d in col.documents]
            self.assertEqual(paths, ["a.md", "b.md"])

    def test_doc_id_tiebreak(self) -> None:
        entries = [
            CollectionEntry(doc_id="b" * 64, path="same.md"),
            CollectionEntry(doc_id="a" * 64, path="same.md"),
        ]
        ordered = _sort_collection_entries(entries)
        self.assertEqual([e.doc_id for e in ordered], ["a" * 64, "b" * 64])

    def test_mixed_path_and_tiebreak(self) -> None:
        entries = [
            CollectionEntry(doc_id="b" * 64, path="z.md"),
            CollectionEntry(doc_id="b" * 64, path="a.md"),
            CollectionEntry(doc_id="b" * 64, path="same.md"),
            CollectionEntry(doc_id="a" * 64, path="same.md"),
        ]
        ordered = _sort_collection_entries(entries)
        self.assertEqual(
            [(e.path, e.doc_id) for e in ordered],
            [
                ("a.md", "b" * 64),
                ("same.md", "a" * 64),
                ("same.md", "b" * 64),
                ("z.md", "b" * 64),
            ],
        )


if __name__ == "__main__":
    unittest.main()
