from pathlib import Path

import pytest

from mcard.loader import load_file_to_collection
from mcard.model.card_collection import CardCollection


def test_loader_docs():
    # Setup
    base_dir = Path(__file__).parent.parent
    docs_path = base_dir / "docs"

    if not docs_path.exists():
        pytest.skip(f"Docs directory not found at {docs_path}")

    collection = CardCollection(db_path=":memory:")

    # Execution
    print(f"Loading docs from: {docs_path}")
    response = load_file_to_collection(docs_path, collection, recursive=True)

    # Verification
    assert isinstance(response, dict)
    metrics = response.get("metrics")
    results = response.get("results")

    assert metrics is not None
    assert metrics["files_count"] > 0
    # directories_count might be 0 if docs has no subdirs (unlikely) but let's assume valid > 0 or >=0
    assert metrics["directories_count"] >= 0

    print(f"Metrics: {metrics}")

    # Handle Verification
    # Check if a few files have their handles registered correctly
    success_handles = 0
    for res in results[:10]:  # Check first 10
        filename = res["filename"]
        file_hash = res["hash"]

        # Try resolving by filename
        resolved = collection.resolve_handle(filename)

        if resolved == file_hash:
            success_handles += 1
        else:
            # Maybe it used relative path handle due to collision?
            # We can't easily know the relative path here without recalculating,
            # but we can try to find if ANY handle points to this hash?
            pass

    assert success_handles > 0, "No handles were resolvable by filename"
