"""School advanced acceptance using generated Q/E and the real SQLite provider."""
import asyncio
import json
import os
import sys
from datetime import date
from Q import Q
from E import E
from runtime_module import GENERATED_RUNTIME_MODULE
from teaql.provider.sqlite import create_sqlite_service
from teaql.runtime import UserContext


def report(case, value):
    print("SCHOOL_CASE " + json.dumps({"case": case, "value": value}))


async def load(context, name):
    entity = await (Q.schools().with_name_is(name).limit(2)
        .comment("Load complete School state for mutation").purpose("Preserve optimistic version")
        .execute_for_one(context))
    assert entity is not None
    return entity


async def main():
    phase = sys.argv[1]
    assert phase in ("bootstrap", "transaction", "worker", "seed", "query", "update", "read-update", "delete", "read-delete")
    context = UserContext.new().install(GENERATED_RUNTIME_MODULE)
    context.insert_resource("dataService", create_sqlite_service(os.environ["SCHOOL_DATABASE"]))
    if phase != "worker": await context.ensure_schema()
    if phase == "seed":
        fixture = json.load(open(os.environ["SCHOOL_FIXTURE"]))
        roots = await (Q.platforms_minimal().with_id_is(1).limit(2)
            .comment("Load the seeded School root").purpose("Seed advanced School scenarios")
            .execute_for_list(context))
        assert len(roots) == 1
        for item in fixture["schools"]:
            school = (Q.schools().comment("Create an advanced School fixture row")
                .purpose("Seed advanced School scenarios").new_entity(context))
            school.update_platform(roots[0])
            if item["type"] == "PRIMARY": school.update_school_type_to_primary()
            else: school.update_school_type_to_secondary()
            school.update_name(item["name"])
            school.update_address(fixture["address"])
            school.update_established_date(date.fromisoformat(fixture["establishedDate"]))
            school.update_student_capacity(item["capacity"])
            school.update_active(item["active"])
            await school.audit_as("Seed the advanced School fixture").save(context)


    # scenario: transaction-commit, transaction-rollback
    if phase == "transaction":
        rollback = os.environ["SCHOOL_SCENARIO"] == "transaction-rollback"
        root = await (Q.platforms().select_school_list_with(Q.schools().with_name_is("Riverside Primary School").limit(2))
            .limit(2).comment("Load the Platform and School transaction graph").purpose("Verify atomic graph writes").execute_for_one(context))
        assert root is not None
        child = root.school_list()[0]
        if rollback:
            winner = await load(context, "Riverside Primary School")
            winner.update_student_capacity(801)
            await winner.audit_as("Advance School before the stale graph").save(context)
        root.update_name("Transactional Campus")
        child.update_student_capacity(810)
        print("SCHOOL_GRAPH_ATTEMPT", flush=True)
        rejected = False
        try:
            await root.audit_as("Revise Platform and School atomically").save(context)
        except Exception as error:
            assert rollback and any(w in str(error).lower() for w in ("version", "optimistic", "conflict", "stale", "authoritative persisted state")), str(error)
            rejected = True
        report(os.environ["SCHOOL_SCENARIO"], {"rejected": rejected})
    # scenario: concurrent-same, concurrent-distinct
    if phase == "worker":
        target, worker, barrier = os.environ["SCHOOL_TARGET"], os.environ["SCHOOL_WORKER"], os.environ["SCHOOL_BARRIER"]
        row = await load(context, target)
        observed_version = E.school(row).version().eval()
        with open(f"{barrier}/{worker}.ready", "w") as ready: json.dump({"observedVersion": observed_version}, ready)
        deadline = asyncio.get_running_loop().time() + 30
        while not os.path.exists(f"{barrier}/release"):
            assert asyncio.get_running_loop().time() < deadline, "Barrier timeout"
            await asyncio.sleep(0.01)
        row.update_student_capacity(811 if worker == "a" else 822)
        outcome, conflict_reason = "committed", ""
        try:
            await row.audit_as("Concurrent School capacity revision").save(context)
        except Exception as error:
            assert any(w in str(error).lower() for w in ("version", "optimistic", "conflict", "stale", "authoritative persisted state")), str(error)
            outcome, conflict_reason = "conflict", str(error)
        print("SCHOOL_WORKER " + json.dumps({"worker": worker, "target": target, "observedVersion": observed_version, "outcome": outcome, "conflictReason": conflict_reason}))

    if phase == "query":
        # scenario: continuous-ascending
        if os.environ.get("SCHOOL_SCENARIO", "continuous-ascending") == "continuous-ascending":
            pages, plans, totals, observed_counts = [], [], [], []
            for offset, threshold in [(0, 0), (2, 0), (4, 0)]:
                page = await (Q.schools_minimal().select_name().with_student_capacity_greater_than_or_equal_to(threshold)
                    .order_by_id_ascending().offset(offset).limit(2).optimize_for_continuous_page_fetch_with("continuous-ascending", 60)
                    .comment("Browse School pagination").purpose("Verify continuous-ascending").execute_for_list(context))
                pages.append([E.school(s).name().eval() for s in page])
                plans.append(context.continuous_page_plan())

            report("continuous-ascending", {"pages": pages, "plans": plans})
        # scenario: continuous-descending
        if os.environ.get("SCHOOL_SCENARIO", "continuous-descending") == "continuous-descending":
            pages, plans, totals, observed_counts = [], [], [], []
            for offset, threshold in [(0, 0), (2, 0), (4, 0)]:
                page = await (Q.schools_minimal().select_name().with_student_capacity_greater_than_or_equal_to(threshold)
                    .order_by_id_descending().offset(offset).limit(2).optimize_for_continuous_page_fetch_with("continuous-descending", 60)
                    .comment("Browse School pagination").purpose("Verify continuous-descending").execute_for_list(context))
                pages.append([E.school(s).name().eval() for s in page])
                plans.append(context.continuous_page_plan())

            report("continuous-descending", {"pages": pages, "plans": plans})
        # scenario: continuous-cache-miss
        if os.environ.get("SCHOOL_SCENARIO", "continuous-cache-miss") == "continuous-cache-miss":
            pages, plans, totals, observed_counts = [], [], [], []
            for offset, threshold in [(2, 0), (4, 0)]:
                page = await (Q.schools_minimal().select_name().with_student_capacity_greater_than_or_equal_to(threshold)
                    .order_by_id_ascending().offset(offset).limit(2).optimize_for_continuous_page_fetch_with("continuous-cache-miss", 60)
                    .comment("Browse School pagination").purpose("Verify continuous-cache-miss").execute_for_list(context))
                pages.append([E.school(s).name().eval() for s in page])
                plans.append(context.continuous_page_plan())

            report("continuous-cache-miss", {"pages": pages, "plans": plans})
        # scenario: id-set-jump
        if os.environ.get("SCHOOL_SCENARIO", "id-set-jump") == "id-set-jump":
            pages, plans, totals, observed_counts = [], [], [], []
            for offset, threshold in [(4, 0), (0, 0), (2, 0), (6, 0)]:
                page = await (Q.schools_minimal().select_name().with_student_capacity_greater_than_or_equal_to(threshold)
                    .order_by_student_capacity_descending().order_by_name_ascending().order_by_id_ascending().offset(offset).limit(2).optimize_pagination_with_id_set_config("id-set-jump", 60, 100).count()
                    .comment("Browse School pagination").purpose("Verify id-set-jump").execute_for_list(context))
                pages.append([E.school(s).name().eval() for s in page])
                plans.append(context.id_set_plan())
                totals.append(page.total_count); observed_counts.append(context.id_set_count()[0])
            report("id-set-jump", {"pages": pages, "plans": plans, "totals": totals, "observedCounts": observed_counts})
        # scenario: id-set-empty
        if os.environ.get("SCHOOL_SCENARIO", "id-set-empty") == "id-set-empty":
            pages, plans, totals, observed_counts = [], [], [], []
            for offset, threshold in [(0, 100000), (2, 100000)]:
                page = await (Q.schools_minimal().select_name().with_student_capacity_greater_than_or_equal_to(threshold)
                    .order_by_student_capacity_descending().order_by_name_ascending().order_by_id_ascending().offset(offset).limit(2).optimize_pagination_with_id_set_config("id-set-empty", 60, 100).count()
                    .comment("Browse School pagination").purpose("Verify id-set-empty").execute_for_list(context))
                pages.append([E.school(s).name().eval() for s in page])
                plans.append(context.id_set_plan())
                totals.append(page.total_count); observed_counts.append(context.id_set_count()[0])
            report("id-set-empty", {"pages": pages, "plans": plans, "totals": totals, "observedCounts": observed_counts})
        # scenario: id-set-overflow
        if os.environ.get("SCHOOL_SCENARIO", "id-set-overflow") == "id-set-overflow":
            pages, plans, totals, observed_counts = [], [], [], []
            for offset, threshold in [(2, 0)]:
                page = await (Q.schools_minimal().select_name().with_student_capacity_greater_than_or_equal_to(threshold)
                    .order_by_student_capacity_descending().order_by_name_ascending().order_by_id_ascending().offset(offset).limit(2).optimize_pagination_with_id_set_config("id-set-overflow", 60, 3).count()
                    .comment("Browse School pagination").purpose("Verify id-set-overflow").execute_for_list(context))
                pages.append([E.school(s).name().eval() for s in page])
                plans.append(context.id_set_plan())
                totals.append(page.total_count); observed_counts.append(context.id_set_count()[0])
            report("id-set-overflow", {"pages": pages, "plans": plans, "totals": totals, "observedCounts": observed_counts})
        # scenario: id-set-isolation
        if os.environ.get("SCHOOL_SCENARIO", "id-set-isolation") == "id-set-isolation":
            pages, plans, totals, observed_counts = [], [], [], []
            for offset, threshold in [(0, 500), (0, 1000), (0, 500)]:
                page = await (Q.schools_minimal().select_name().with_student_capacity_greater_than_or_equal_to(threshold)
                    .order_by_student_capacity_descending().order_by_name_ascending().order_by_id_ascending().offset(offset).limit(2).optimize_pagination_with_id_set_config("id-set-isolation", 60, 100).count()
                    .comment("Browse School pagination").purpose("Verify id-set-isolation").execute_for_list(context))
                pages.append([E.school(s).name().eval() for s in page])
                plans.append(context.id_set_plan())
                totals.append(page.total_count); observed_counts.append(context.id_set_count()[0])
            report("id-set-isolation", {"pages": pages, "plans": plans, "totals": totals, "observedCounts": observed_counts})
        # scenario: pagination
        if os.environ.get("SCHOOL_SCENARIO", "pagination") == "pagination":
            page = await (Q.schools_minimal().select_name().which_are_active()
                .with_student_capacity_greater_than_or_equal_to(500)
                .order_by_student_capacity_descending().order_by_id_ascending().offset(1).limit(2).count()
                .comment("Page active schools by capacity").purpose("Review the School directory")
                .execute_for_list(context))
            report("pagination", {"names": [E.school(s).name().eval() for s in page], "total": page.total_count})
        # scenario: relations
        if os.environ.get("SCHOOL_SCENARIO", "relations") == "relations":
            rows = await (Q.schools_minimal().select_name().with_name_is("Riverside Primary School")
                .select_school_type_with(Q.school_types_minimal().select_code())
                .select_platform_with(Q.platforms_minimal().select_name()).limit(2)
                .comment("Load School type and platform").purpose("Review loaded School relations")
                .execute_for_list(context))
            assert len(rows) == 1
            school = rows[0]
            report("relations", {"school": E.school(school).name().eval(),
                "type": E.school_type(E.school(school).school_type().eval()).code().eval(),
                "platform": E.platform(E.school(school).platform().eval()).name().eval()})
        # scenario: groups
        if os.environ.get("SCHOOL_SCENARIO", "groups") == "groups":
            groups = await (Q.schools().group_by_school_type().count_as("count")
                .sum_student_capacity_as("total").avg_student_capacity_as("average")
                .limit(10)
                .comment("Group School capacity by type").purpose("Verify provider aggregation")
                .execute_for_rows(context))
            report("groups", [{"type": int(r["school_type"]), "count": int(r["count"]),
                "total": float(r["total"]), "average": float(r["average"])} for r in groups])
        # scenario: relation-metrics
        if os.environ.get("SCHOOL_SCENARIO", "relation-metrics") == "relation-metrics":
            cards = await (Q.school_types_minimal().select_code().count_schools_as("count")
                .sum_student_capacity_of_schools_as("total", Q.schools()).order_by_code_ascending().limit(10)
                .comment("Calculate SchoolType relation metrics").purpose("Verify provider relation aggregation")
                .execute_for_rows(context))
            report("relation-metrics", {r["code"]: {"count": int(r["count"]), "total": float(r["total"])} for r in cards})
        # scenario: facets
        if os.environ.get("SCHOOL_SCENARIO", "facets") == "facets":
            async def facets(include_all):
                return await (Q.schools_minimal().select_name().with_name_is("Riverside Primary School")
                    .facet_by_school_type_as("types", Q.school_types_minimal().select_code().count_schools_as("count"), include_all)
                    .facet_by_platform_as("platforms", Q.platforms_minimal().select_name().count_schools_as("count"), False)
                    .order_by_id_ascending().limit(2)
                    .comment("Facet the matching School set").purpose("Compare zero and matched buckets")
                    .execute_for_list(context))
            all_rows, matched = await facets(True), await facets(False)
            report("facets", {"includeAll": {r["code"]: int(r["count"]) for r in all_rows.facet("types")},
                "matchedOnly": {r["code"]: int(r["count"]) for r in matched.facet("types")},
                "platforms": {r["name"]: int(r["count"]) for r in all_rows.facet("platforms")},
                "rows": [E.school(s).name().eval() for s in all_rows]})
        # scenario: page-boundaries
        if os.environ.get("SCHOOL_SCENARIO", "page-boundaries") == "page-boundaries":
            pages, totals = [], []
            for offset in (0, 2, 4, 6):
                page = await (Q.schools_minimal().select_name()
                    .order_by_student_capacity_descending().order_by_name_ascending().order_by_id_ascending().offset(offset).limit(2).count()
                    .comment("Traverse School pages including an empty tail").purpose("Verify stable page boundaries")
                    .execute_for_list(context))
                pages.append([E.school(s).name().eval() for s in page]); totals.append(page.total_count)
            report("page-boundaries", {"pages": pages, "totals": totals})
        # scenario: relation-predicates
        if os.environ.get("SCHOOL_SCENARIO", "relation-predicates") == "relation-predicates":
            matching = await (Q.schools_minimal().select_name()
                .with_school_type_matching(Q.school_types_minimal().with_code_is("PRIMARY"))
                .order_by_name_ascending().limit(10).comment("Match School type by child request")
                .purpose("Verify relation predicate semantics").execute_for_list(context))
            excluding = await (Q.schools_minimal().select_name()
                .without_school_type_matching(Q.school_types_minimal().with_code_is("PRIMARY"))
                .order_by_name_ascending().limit(10).comment("Exclude School type by child request")
                .purpose("Verify negative relation predicates").execute_for_list(context))
            nested = await (Q.schools_minimal().select_name()
                .with_school_type_matching(Q.school_types_minimal().with_code_is("PRIMARY")
                    .with_platform_matching(Q.platforms_minimal().with_name_is("Campus Learning Platform")))
                .order_by_name_ascending().limit(10).comment("Match School through type and platform")
                .purpose("Verify two-level relation predicates").execute_for_list(context))
            report("relation-predicates", {"matching": [E.school(s).name().eval() for s in matching],
                "excluding": [E.school(s).name().eval() for s in excluding], "nested": [E.school(s).name().eval() for s in nested]})
        # scenario: blank-intent
        if os.environ.get("SCHOOL_SCENARIO", "blank-intent") == "blank-intent":
            rejected = []
            for comment, purpose in [(" ", "Verify blank comment rejection"), ("Check blank purpose rejection", " ")]:
                denied = False
                try:
                    await Q.schools_minimal().limit(1).comment(comment).purpose(purpose).execute_for_list(context)
                except Exception as error:
                    assert any(word in str(error).lower() for word in ("comment", "purpose", "intent")), str(error)
                    denied = True
                rejected.append(denied)
            report("blank-intent", {"blankComment": rejected[0], "blankPurpose": rejected[1]})
        # scenario: empty-page
        if os.environ.get("SCHOOL_SCENARIO", "empty-page") == "empty-page":
            page = await (Q.schools_minimal().select_name().with_name_is("No such School")

                .order_by_student_capacity_descending().order_by_id_ascending().offset(1).limit(2).count()
                .comment("Read a School filter with no matches").purpose("Verify empty page count")
                .execute_for_list(context))
            report("empty-page", {"names": [E.school(s).name().eval() for s in page], "total": page.total_count})
        # scenario: filtered-groups
        if os.environ.get("SCHOOL_SCENARIO", "filtered-groups") == "filtered-groups":
            groups = await (Q.schools().which_are_active().with_student_capacity_greater_than_or_equal_to(500).group_by_school_type().count_as("count")
                .sum_student_capacity_as("total").avg_student_capacity_as("average")
                .limit(10)
                .comment("Aggregate active Schools with capacity at least 500").purpose("Verify provider aggregation")
                .execute_for_rows(context))
            report("filtered-groups", [{"type": int(r["school_type"]), "count": int(r["count"]),
                "total": float(r["total"]), "average": float(r["average"])} for r in groups])
        # scenario: filtered-children
        if os.environ.get("SCHOOL_SCENARIO", "filtered-children") == "filtered-children":
            types = await (Q.school_types_minimal().select_code()
                .select_school_list_with(Q.schools_minimal().select_name().which_are_not_active()
                    .order_by_student_capacity_descending().order_by_id_ascending().limit(2))
                .order_by_code_ascending().limit(10)
                .comment("Load inactive Schools for each type").purpose("Preserve parents with empty child lists")
                .execute_for_list(context))
            report("filtered-children", {E.school_type(t).code().eval(): [E.school_type(t).school_list().get(i).name().eval()
                for i in range(E.school_type(t).school_list().size().eval())] for t in types})
        # scenario: empty-facets
        if os.environ.get("SCHOOL_SCENARIO", "empty-facets") == "empty-facets":
            async def facets(include_all):
                return await (Q.schools_minimal().select_name().with_name_is("No such School")
                    .facet_by_school_type_as("types", Q.school_types_minimal().select_code().count_schools_as("count"), include_all)
                    .facet_by_platform_as("platforms", Q.platforms_minimal().select_name().count_schools_as("count"), False)
                    .order_by_id_ascending().limit(2)
                    .comment("Facet the matching School set").purpose("Compare zero and matched buckets")
                    .execute_for_list(context))
            all_rows, matched = await facets(True), await facets(False)
            report("empty-facets", {"includeAll": {r["code"]: int(r["count"]) for r in all_rows.facet("types")},
                "matchedOnly": {r["code"]: int(r["count"]) for r in matched.facet("types")},
                "platforms": {r["name"]: int(r["count"]) for r in all_rows.facet("platforms")},
                "rows": [E.school(s).name().eval() for s in all_rows]})
        # scenario: top-n
        if os.environ.get("SCHOOL_SCENARIO", "top-n") == "top-n":
            types = await (Q.school_types_minimal().select_code()
                .select_school_list_with(Q.schools_minimal().select_name()
                    .order_by_student_capacity_descending().order_by_id_ascending().limit(2))
                .order_by_code_ascending().limit(10)
                .comment("Load the two largest schools for each type").purpose("Verify Top-N across two parents")
                .execute_for_list(context))
            report("top-n", {E.school_type(t).code().eval(): [E.school_type(t).school_list().get(i).name().eval()
                for i in range(E.school_type(t).school_list().size().eval())] for t in types})

    # scenario: update
    if phase == "update":
        school = await load(context, "Riverside Primary School")
        stale = await load(context, "Riverside Primary School")
        before = E.school(school).version().eval()
        school.update_student_capacity(950)
        school = await school.audit_as("Approve School capacity revision").save(context)
        report("update", {"before": before, "after": E.school(school).version().eval(),
            "capacity": E.school(school).student_capacity().eval()})
        stale.update_student_capacity(999)
        rejected = False
        try:
            await stale.audit_as("Reject stale School capacity revision").save(context)
        except Exception as error:
            # 0.3.1 reports a zero-row optimistic update as missing authoritative state.
            assert (str(error) == "Mutation provider did not return authoritative persisted state for School"
                    or any(word in str(error).lower() for word in ("version", "optimistic", "conflict", "stale"))), str(error)
            rejected = True
        report("stale-write", {"rejected": rejected})
    if phase == "read-update":
        school = await load(context, "Riverside Primary School")
        report("read-update", {"capacity": E.school(school).student_capacity().eval(), "version": E.school(school).version().eval()})
    # scenario: delete
    if phase == "delete":
        school = await load(context, "Hill Secondary School")
        school.mark_for_deletion()
        await school.audit_as("Retire inactive School fixture").save(context)
    if phase == "delete" or (phase == "read-delete" and os.environ.get("SCHOOL_SCENARIO", "read-delete") == "read-delete"):
        visible = await (Q.schools_minimal().with_name_is("Hill Secondary School").limit(2)
            .comment("Check the retired School is hidden").purpose("Verify soft deletion visibility")
            .execute_for_list(context))
        value = {"visible": len(visible)}
        if phase == "read-delete":
            deleted = await (Q.schools_minimal().deleted_rows_only().with_name_is("Hill Secondary School").limit(2)
                .comment("Read the School tombstone").purpose("Verify persisted deletion intent")
                .execute_for_list(context))
            value["deleted"] = len(deleted)
        report(phase, value)
    if phase == "read-delete":
        # scenario: deleted-groups
        if os.environ.get("SCHOOL_SCENARIO", "deleted-groups") == "deleted-groups":
            groups = await (Q.schools().group_by_school_type().count_as("count")
                .sum_student_capacity_as("total").avg_student_capacity_as("average")
                .limit(10)
                .comment("Aggregate surviving Schools after deletion").purpose("Verify provider aggregation")
                .execute_for_rows(context))
            report("deleted-groups", [{"type": int(r["school_type"]), "count": int(r["count"]),
                "total": float(r["total"]), "average": float(r["average"])} for r in groups])
        # scenario: deleted-metrics
        if os.environ.get("SCHOOL_SCENARIO", "deleted-metrics") == "deleted-metrics":
            cards = await (Q.school_types_minimal().select_code().count_schools_as("count")
                .sum_student_capacity_of_schools_as("total", Q.schools()).order_by_code_ascending().limit(10)
                .comment("Calculate relation metrics after School deletion").purpose("Verify provider relation aggregation")
                .execute_for_rows(context))
            report("deleted-metrics", {r["code"]: {"count": int(r["count"]), "total": float(r["total"])} for r in cards})
        # scenario: deleted-facets
        if os.environ.get("SCHOOL_SCENARIO", "deleted-facets") == "deleted-facets":
            async def facets(include_all):
                return await (Q.schools_minimal().select_name()
                    .facet_by_school_type_as("types", Q.school_types_minimal().select_code().count_schools_as("count"), include_all)
                    .facet_by_platform_as("platforms", Q.platforms_minimal().select_name().count_schools_as("count"), False)
                    .order_by_student_capacity_descending().order_by_id_ascending().limit(2)
                    .comment("Facet the matching School set").purpose("Compare zero and matched buckets")
                    .execute_for_list(context))
            all_rows, matched = await facets(True), await facets(False)
            report("deleted-facets", {"includeAll": {r["code"]: int(r["count"]) for r in all_rows.facet("types")},
                "matchedOnly": {r["code"]: int(r["count"]) for r in matched.facet("types")},
                "platforms": {r["name"]: int(r["count"]) for r in all_rows.facet("platforms")},
                "rows": [E.school(s).name().eval() for s in all_rows]})
        # scenario: deleted-children
        if os.environ.get("SCHOOL_SCENARIO", "deleted-children") == "deleted-children":
            types = await (Q.school_types_minimal().select_code()
                .select_school_list_with(Q.schools_minimal().select_name()
                    .order_by_student_capacity_descending().order_by_id_ascending().limit(2))
                .order_by_code_ascending().limit(10)
                .comment("Load surviving Schools for each type").purpose("Exclude tombstones from ordinary child lists")
                .execute_for_list(context))
            report("deleted-children", {E.school_type(t).code().eval(): [E.school_type(t).school_list().get(i).name().eval()
                for i in range(E.school_type(t).school_list().size().eval())] for t in types})
        # scenario: deleted-child-tombstones
        if os.environ.get("SCHOOL_SCENARIO", "deleted-child-tombstones") == "deleted-child-tombstones":
            types = await (Q.school_types_minimal().select_code()
                .select_school_list_with(Q.schools_minimal().select_name().deleted_rows_only()
                    .order_by_student_capacity_descending().order_by_id_ascending().limit(2))
                .order_by_code_ascending().limit(10)
                .comment("Load retired Schools for each live type").purpose("Keep child deletion scope separate from parent visibility")
                .execute_for_list(context))
            report("deleted-child-tombstones", {E.school_type(t).code().eval(): [E.school_type(t).school_list().get(i).name().eval()
                for i in range(E.school_type(t).school_list().size().eval())] for t in types})
    print(f"SCHOOL_OK phase={phase}")


if __name__ == "__main__":
    asyncio.run(main())
