from __future__ import annotations

from datetime import datetime, timedelta, timezone
from pathlib import Path

from cf_ontology.pipeline_states_store import PipelineStateStore


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


def test_pipeline_runs_schema_contains_session_columns(tmp_path: Path) -> None:
    store = _make_store(tmp_path)
    con = store._connect(read_only=True)
    try:
        rows = con.execute("PRAGMA table_info('pipeline_runs')").fetchall()
    finally:
        con.close()
    column_names = {str(row[1]) for row in rows}
    assert "session_id" in column_names
    assert "session_run_index" in column_names


def test_event_consumption_assigns_session_and_monotonic_run_index(tmp_path: Path) -> None:
    store = _make_store(tmp_path)
    con = store._connect(read_only=False)
    try:
        now = datetime(2026, 2, 14, 12, 0, 0, tzinfo=timezone.utc)
        event_id_a, created_a = store.insert_event(
            pipeline_id="pipeline_alpha",
            event_type="manual",
            source="test",
            payload={"case": "session-a"},
            dedupe_key="session-a",
            con=con,
        )
        event_id_b, created_b = store.insert_event(
            pipeline_id="pipeline_alpha",
            event_type="manual",
            source="test",
            payload={"case": "session-b"},
            dedupe_key="session-b",
            con=con,
        )
        assert created_a is True
        assert created_b is True

        consumed_a = store.consume_event_to_run(
            event_id=event_id_a,
            pipeline_rev=1,
            priority=0,
            now=now,
            con=con,
        )
        consumed_b = store.consume_event_to_run(
            event_id=event_id_b,
            pipeline_rev=1,
            priority=0,
            now=now + timedelta(seconds=1),
            con=con,
        )
        assert consumed_a is not None
        assert consumed_b is not None
        run_id_a = str(consumed_a[0])
        run_id_b = str(consumed_b[0])

        rows = con.execute(
            """
            SELECT session_id, session_run_index
            FROM pipeline_runs
            WHERE run_id IN (?, ?)
            ORDER BY session_run_index
            """,
            [run_id_a, run_id_b],
        ).fetchall()
    finally:
        con.close()

    assert len(rows) == 2
    assert rows[0][0] == rows[1][0]
    assert int(rows[0][1]) == 0
    assert int(rows[1][1]) == 1
