"""tests/grounding 공용 fixture.

★`short_id` 는 2026-09-04 부터 **프로젝트 장부**에서 발급된다
(`app.core.entity_identity`). 그 전에는 목록 안 위치(`f"{prefix}{i:02d}"`)라
스텝을 `db=None` 으로 돌릴 수 있었고, **그것이 바로 「2화가 1화를 덮는」
결함**이었다(실측 `da049582`).

이제 스텝이 DB 를 실제로 쓰므로, 이 lane 의 스텝 끝점 시험은 **진짜 세션**을
받아야 발급 계약을 태운다. fake 로 바꾸면 그 계약을 안 태우고 초록만 본다.
"""
from __future__ import annotations

import uuid

import pytest

#: 이 lane 의 스텝 시험이 쓰는 고정 project_id (체크포인트 경로와 같아야 한다).
GROUNDING_TEST_PROJECT_ID = "p"


@pytest.fixture
def project_db():
    """`project_registry` 행이 있는 진짜 세션. 만든 것만 지우고 나간다."""
    from sqlalchemy import text as sql_text

    from app.core.database import SessionLocal, init_db

    init_db()
    session = SessionLocal()
    pid = GROUNDING_TEST_PROJECT_ID
    uid = f"gtest-{uuid.uuid4()}"
    session.execute(sql_text(
        "INSERT INTO user_account (id, username, display_name, password_hash, "
        "role, is_active, created_at, updated_at) VALUES "
        "(:uid, :un, 't', 'x', 'creator', 1, '2026-01-01', '2026-01-01')"
    ), {"uid": uid, "un": f"u_{uid}"})
    session.execute(sql_text(
        "INSERT INTO project_registry (id, name, created_by, created_at, "
        "updated_at) VALUES (:pid, 'grounding-test', :uid, '2026-01-01', "
        "'2026-01-01') ON CONFLICT (id) DO NOTHING"
    ), {"pid": pid, "uid": uid})
    session.commit()
    try:
        yield session
    finally:
        session.rollback()
        for sql in (
            "DELETE FROM project_short_id_counter WHERE project_id = :pid",
            "DELETE FROM entity_episode_link WHERE project_id = :pid",
            "DELETE FROM entity_canon WHERE project_id = :pid",
            "DELETE FROM project_registry WHERE id = :pid",
            "DELETE FROM user_account WHERE id = :uid",
        ):
            try:
                session.execute(sql_text(sql), {"pid": pid, "uid": uid})
                session.commit()
            except Exception:  # noqa: BLE001
                session.rollback()
        session.close()
