from run.initialization import reset_environment


def test_reset_user_subset_scope_only_runs_user_subset_cleanup(monkeypatch):
    calls = []

    monkeypatch.setattr(
        reset_environment,
        "_sb_headers",
        lambda: ("http://192.168.0.94:8000", {"Authorization": "Bearer redacted"}),
    )
    monkeypatch.setattr(
        reset_environment,
        "_assert_reset_allowed",
        lambda url, scope: calls.append(("guard", url, scope)),
    )
    monkeypatch.setattr(
        reset_environment,
        "_clear_user_subset_files",
        lambda: {"files_rows_deleted": 2, "storage_objects_removed": 2, "errors": []},
    )

    def fail_if_called(*_args, **_kwargs):
        raise AssertionError("reset(scope='user-subset') must not clear unrelated tables or databases")

    monkeypatch.setattr(reset_environment, "_clear_tables", fail_if_called)
    monkeypatch.setattr(reset_environment, "_neo4j_drop_all_non_system", fail_if_called)
    monkeypatch.setattr(reset_environment, "_clear_exam_storage", fail_if_called)

    result = reset_environment.reset(scope="user-subset")

    assert calls == [("guard", "http://192.168.0.94:8000", "user-subset")]
    assert result == {
        "scope": "user-subset",
        "user_subset": {"files_rows_deleted": 2, "storage_objects_removed": 2, "errors": []},
    }


def test_reset_accepts_case_insensitive_user_subset_scope(monkeypatch):
    monkeypatch.setattr(reset_environment, "_sb_headers", lambda: ("http://192.168.0.94:8000", {}))
    monkeypatch.setattr(reset_environment, "_assert_reset_allowed", lambda *_args, **_kwargs: None)
    monkeypatch.setattr(
        reset_environment,
        "_clear_user_subset_files",
        lambda: {"files_rows_deleted": 0, "storage_objects_removed": 0, "errors": []},
    )

    assert reset_environment.reset(scope="USER-SUBSET") == {
        "scope": "user-subset",
        "user_subset": {"files_rows_deleted": 0, "storage_objects_removed": 0, "errors": []},
    }
