from __future__ import annotations

from datetime import datetime, timezone
from pathlib import Path

from cf_ontology import pipeline_state_runtime as runtime
from cf_ontology.pipeline_states_store import PipelineStateStore


def _make_store(tmp_path: Path) -> PipelineStateStore:
    semantics_dir = tmp_path / "semantics"
    semantics_dir.mkdir(parents=True, exist_ok=True)
    db_path = semantics_dir / "cf-pipeline-states.duckdb"
    store = PipelineStateStore(db_path=db_path, semantics_dir=semantics_dir)
    store.init_schema()
    return store


def test_runtime_has_no_direct_enqueue_helper() -> None:
    assert not hasattr(runtime, "_enqueue_run")


def test_consume_requires_pending_event_record(tmp_path: Path) -> None:
    store = _make_store(tmp_path)
    con = store._connect(read_only=False)
    try:
        consumed = store.consume_event_to_run(
            event_id="missing-event-id",
            pipeline_rev=1,
            priority=0,
            now=datetime.now(timezone.utc),
            con=con,
        )
        run_count = con.execute("SELECT COUNT(*) FROM pipeline_runs").fetchone()
        queue_count = con.execute("SELECT COUNT(*) FROM run_queue").fetchone()
    finally:
        con.close()

    assert consumed is None
    assert run_count is not None and int(run_count[0]) == 0
    assert queue_count is not None and int(queue_count[0]) == 0


def test_event_consumption_persists_bidirectional_registration(tmp_path: Path) -> None:
    store = _make_store(tmp_path)
    event_id, created = store.insert_event(
        pipeline_id="pipe-a",
        event_type="manual",
        source="test",
        payload={"case": "single-entrypoint"},
        dedupe_key="single-entrypoint-1",
    )
    assert created is True

    consumed = store.consume_event_to_run(
        event_id=event_id,
        pipeline_rev=7,
        priority=3,
        now=datetime.now(timezone.utc),
    )
    assert consumed is not None
    run_id, queue_id, pipeline_id = consumed
    assert pipeline_id == "pipe-a"

    con = store._connect(read_only=True)
    try:
        event_row = con.execute(
            "SELECT run_id, status FROM run_events WHERE event_id = ?",
            [event_id],
        ).fetchone()
        run_row = con.execute(
            "SELECT triggered_by_event_id, pipeline_id, status FROM pipeline_runs WHERE run_id = ?",
            [run_id],
        ).fetchone()
        queue_row = con.execute(
            "SELECT queue_id FROM run_queue WHERE run_id = ?",
            [run_id],
        ).fetchone()
    finally:
        con.close()

    assert event_row is not None
    assert str(event_row[0]) == str(run_id)
    assert str(event_row[1]) == "consumed"
    assert run_row is not None
    assert str(run_row[0]) == str(event_id)
    assert str(run_row[1]) == "pipe-a"
    assert str(run_row[2]) == "queued"
    assert queue_row is not None
    assert str(queue_row[0]) == str(queue_id)
