from pathlib import Path

ROOT = Path(__file__).resolve().parent
YELLOW = (ROOT / 'yellow.php').read_text(encoding='utf-8')
FUNC = (ROOT / 'yellow_func.php').read_text(encoding='utf-8')
DB = (ROOT / 'yy_db_conn.php').read_text(encoding='utf-8')
COMPAT = (ROOT / 'yellow_schema_v46_compat.sql').read_text(encoding='utf-8')


def test_media_insert_has_stage_diagnostics() -> None:
    for token in [
        "$yellow_error_stage = 'schema_check'",
        "$yellow_error_stage = 'master_upsert'",
        "$yellow_error_stage = 'user_download_upsert'",
        "$yellow_error_stage = 'collect_event_upsert'",
        "yellow_error('schema_mismatch'",
        "catch (Throwable $e)",
        "yellow_exception_payload($e, $yellow_error_stage)",
    ]:
        assert token in YELLOW, token


def test_schema_check_mode_and_required_columns_exist() -> None:
    assert "if ($mode === 'schema_check')" in YELLOW
    for token in [
        'function yellow_table_columns',
        'function yellow_schema_diagnostic',
        'function yellow_media_schema_diagnostics',
        "'ig_media_collect_event'",
        "'pass_id'",
        "'rank_label'",
        "'filename_stem'",
    ]:
        assert token in FUNC, token


def test_api_does_not_emit_html_errors() -> None:
    assert "define('YELLOW_API_MODE', true)" in FUNC
    assert "defined('YELLOW_API_MODE') && YELLOW_API_MODE" in DB
    assert "ini_set('display_errors', '0')" in DB


def test_compat_migration_is_non_destructive() -> None:
    upper = COMPAT.upper()
    for forbidden in ['DROP TABLE', 'TRUNCATE TABLE', 'DELETE FROM']:
        assert forbidden not in upper.replace('-- 금지: DROP TABLE, TRUNCATE, DELETE를 사용하지 않습니다.'.upper(), '')
    assert 'CREATE TABLE IF NOT EXISTS `ig_media_collect_event`' in COMPAT
    assert 'information_schema.COLUMNS' in COMPAT
    assert 'ALTER TABLE `ig_media_collect_event` ADD COLUMN' in COMPAT
    assert 'ADD UNIQUE KEY `uq_event_key` (`event_key`)' in COMPAT
