"""Tests for pmq Python layer."""
import tempfile
from pathlib import Path

import pytest


# -- Import tests -------------------------------------------------------------

def test_import_build():
    from pmq._build import default_data_dir, flock, is_fresh, write_build_date
    assert callable(default_data_dir)

def test_import_tables():
    from pmq._tables import ALL_TABLES, ftp_fingerprint, compact_table
    assert len(ALL_TABLES) == 30

def test_import_aux():
    from pmq._aux import build_aux_table, _BUILDERS
    assert set(_BUILDERS.keys()) == {"journal", "deleted_pmid_list", "computed_author"}

def test_import_pubmed():
    from pmq import PubMed, __version__
    assert __version__

def test_import_rlm():
    from pmq.rlm import analyze
    assert callable(analyze)


# -- Table list ---------------------------------------------------------------

def test_xml_tables_count():
    from pmq._tables import _XML_TABLES, AUX_TABLES, ALL_TABLES
    assert len(_XML_TABLES) == 27
    assert len(AUX_TABLES) == 3
    assert len(ALL_TABLES) == 30

def test_no_duplicate_tables():
    from pmq._tables import ALL_TABLES
    assert len(ALL_TABLES) == len(set(ALL_TABLES))

def test_core_tables_subset():
    from pmq._tables import _CORE_TABLES, ALL_TABLES
    for t in _CORE_TABLES:
        assert t in ALL_TABLES

def test_table_has_data_missing():
    from pmq._tables import table_has_data
    with tempfile.TemporaryDirectory() as d:
        assert not table_has_data(Path(d), "citation")


# -- flock --------------------------------------------------------------------

def test_flock_basic():
    from pmq._build import flock
    with tempfile.TemporaryDirectory() as d:
        lockfile = Path(d) / "test.lock"
        with flock(lockfile):
            assert lockfile.exists()

def test_flock_reentrant_different_files():
    from pmq._build import flock
    with tempfile.TemporaryDirectory() as d:
        with flock(Path(d) / "a.lock"):
            with flock(Path(d) / "b.lock"):
                pass


# -- Build freshness ----------------------------------------------------------

def test_write_and_check_freshness():
    from pmq._build import is_fresh, write_build_date
    with tempfile.TemporaryDirectory() as d:
        dd = Path(d)
        assert not is_fresh(dd)
        write_build_date(dd)
        assert is_fresh(dd)

def test_stale_build():
    from pmq._build import is_fresh
    with tempfile.TemporaryDirectory() as d:
        dd = Path(d)
        (dd / '.latest-build-date').write_text("2020-01-01T00:00:00+00:00")
        assert not is_fresh(dd)


# -- Binary finder -------------------------------------------------------------

def test_find_binary_does_not_crash():
    from pmq._build import _find_binary
    try:
        path = _find_binary()
        assert Path(path).is_file()
    except RuntimeError as e:
        assert "pmq-core not found" in str(e)


# -- PubMed class basics -------------------------------------------------------

def test_pubmed_init():
    from pmq import PubMed
    with tempfile.TemporaryDirectory() as d:
        db = PubMed(data_dir=d)
        assert db.data_dir == Path(d)
        assert db._through is None

def test_pubmed_through():
    from pmq import PubMed
    with tempfile.TemporaryDirectory() as d:
        db = PubMed(data_dir=d, through="2024")
        assert db._through == "2024"


# -- Sort orders ---------------------------------------------------------------

def test_citation_sort_order():
    from pmq._tables import _SORT_ORDERS, _DEFAULT_SORT
    assert "citation" in _SORT_ORDERS
    assert "pmid" in _SORT_ORDERS["citation"]
    assert _DEFAULT_SORT == "1"
