"""
Tests: Focus Area Nutzungstypen (Migration 036, Router-Helfer).

Ohne MITAI_INTEGRATION_DB=1 werden nur SQL-Datei und reine Python-Helfer geprüft.
Mit gesetztem Flag optional Verifikation gegen eine PostgreSQL-Instanz (Migration 036 angewendet).
"""
from __future__ import annotations

import os
import sys
import uuid
from pathlib import Path

import pytest

BACKEND_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(BACKEND_ROOT))


def test_migration_036_defines_schema_and_seeds_keys():
    p = BACKEND_ROOT / "migrations" / "036_focus_area_usage_types.sql"
    assert p.is_file(), f"expected {p}"
    text = p.read_text(encoding="utf-8")
    assert "CREATE TABLE IF NOT EXISTS focus_area_usage_types" in text
    assert "CREATE TABLE IF NOT EXISTS focus_area_definition_usage_types" in text
    for key in (
        "goal_priority",
        "expected_training_effect",
        "concrete_training_contribution",
    ):
        assert key in text
    assert "ON CONFLICT (key) DO NOTHING" in text
    # Explizit: kein automatisches Befüllen der M:N-Tabelle
    assert "INSERT INTO focus_area_definition_usage_types" not in text


def test_coerce_usage_type_keys_normalizes_values():
    from focus_area_usage_helpers import coerce_usage_type_keys

    assert coerce_usage_type_keys(None) == []
    assert coerce_usage_type_keys([]) == []
    assert coerce_usage_type_keys(["goal_priority", "expected_training_effect"]) == [
        "goal_priority",
        "expected_training_effect",
    ]
    assert coerce_usage_type_keys('["concrete_training_contribution"]') == [
        "concrete_training_contribution"
    ]


@pytest.mark.skipif(
    os.getenv("MITAI_INTEGRATION_DB") != "1",
    reason="Set MITAI_INTEGRATION_DB=1 plus DB_* env to run DB checks (nur Dev/CI!)",
)
def test_integration_focus_area_usage_types_seeded_and_junction_writable():
    """Nur gegen Dev-DB ausführen. Nutzt temporäre focus_area_definitions-Zeile, keine bestehenden Daten."""
    from db import get_db, get_cursor
    from focus_area_usage_helpers import coerce_usage_type_keys

    tmp_id = str(uuid.uuid4())
    tmp_key = f"tmp_usage_{tmp_id[:8]}"

    with get_db() as conn:
        cur = get_cursor(conn)
        cur.execute(
            """
            SELECT key FROM focus_area_usage_types
            ORDER BY sort_order, key
            """
        )
        keys = [row["key"] for row in cur.fetchall()]
        assert keys == [
            "goal_priority",
            "expected_training_effect",
            "concrete_training_contribution",
        ]

        cur.execute(
            """
            INSERT INTO focus_area_definitions
            (id, key, name_de, category, is_active)
            VALUES (%s, %s, 'tmp_test_usage', 'custom', false)
            """,
            (tmp_id, tmp_key),
        )

        cur.execute(
            """
            SELECT COALESCE(
                (
                    SELECT json_agg(faut.key ORDER BY faut.sort_order, faut.key)
                    FROM focus_area_definition_usage_types fadut
                    JOIN focus_area_usage_types faut ON faut.id = fadut.usage_type_id
                    WHERE fadut.focus_area_id = %s
                ),
                '[]'::json
            ) AS allowed_usage_type_keys
            """,
            (tmp_id,),
        )
        assert coerce_usage_type_keys(cur.fetchone()["allowed_usage_type_keys"]) == []

        cur.execute(
            """
            INSERT INTO focus_area_definition_usage_types (focus_area_id, usage_type_id)
            SELECT %s, u.id FROM focus_area_usage_types u WHERE u.key = %s
            """,
            (tmp_id, "goal_priority"),
        )
        cur.execute(
            """
            INSERT INTO focus_area_definition_usage_types (focus_area_id, usage_type_id)
            SELECT %s, u.id FROM focus_area_usage_types u WHERE u.key = %s
            """,
            (tmp_id, "expected_training_effect"),
        )
        cur.execute(
            """
            SELECT COUNT(*) AS n
            FROM focus_area_definition_usage_types
            WHERE focus_area_id = %s
            """,
            (tmp_id,),
        )
        assert cur.fetchone()["n"] == 2

        cur.execute("DELETE FROM focus_area_definitions WHERE id = %s", (tmp_id,))
