"""Application-owned School verification; run from the generated console root."""
import asyncio
import os
import sys
from datetime import date

from Q import Q
from runtime_module import GENERATED_RUNTIME_MODULE
from teaql.provider.sqlite import create_sqlite_service
from teaql.runtime import UserContext


async def main():
    phase = sys.argv[1]
    if phase not in ("bootstrap", "create", "read"):
        raise ValueError("expected bootstrap, create or read")
    context = UserContext.new().install(GENERATED_RUNTIME_MODULE)
    context.insert_resource("dataService", create_sqlite_service(os.environ["SCHOOL_DATABASE"]))
    await context.ensure_schema()

    if phase == "create":
        roots = await (Q.platforms_minimal().with_id_is(1).limit(2)
            .comment("Load the School fixture root").purpose("Verify School persistence")
            .execute_for_list(context))
        assert len(roots) == 1
        school = (Q.schools().comment("Initialize Riverside Primary School")
            .purpose("Verify School persistence").new_entity(context))
        school.update_platform(roots[0])
        school.update_school_type_to_primary()
        school.update_name("Riverside Primary School")
        school.update_address("12 River Road, Springfield")
        school.update_established_date(date(1995, 9, 1))
        school.update_student_capacity(800)
        school.update_active(True)
        await school.audit_as("Create the documented School fixture").save(context)

    rows = await (Q.schools_minimal().select_name()
        .with_name_is("Riverside Primary School").order_by_id_ascending().limit(2)
        .comment("Read the persisted School fixture").purpose("Verify School persistence")
        .execute_for_list(context))
    assert len(rows) == (0 if phase == "bootstrap" else 1)
    print(f"SCHOOL_OK phase={phase}")


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