package main

import (
    "encoding/json"
    "fmt"
    "os"
    "strings"
    "time"
    "github.com/teaql/teaql-golang/core"
    "github.com/teaql/teaql-golang/runtime"
    lib "school-management-service-core-workspace/lib"
    "school-management-service-core-workspace/lib/school"
    "school-management-service-core-workspace/lib/school_type"
)

func must(err error) { if err != nil { panic(err) } }
func need[T any](value T, ok bool) T { if !ok { panic("Required loaded value is null or missing") }; return value }
func report(name string, value any) { data, err := json.Marshal(map[string]any{"case": name, "value": value}); must(err); fmt.Println("SCHOOL_CASE " + string(data)) }
func names(rows *core.SmartList[*school.School]) []string {
    result := []string{}
    for _, row := range rows.Data { result = append(result, need(school.NewSchoolExpression(row).Name().Eval())) }
    return result
}
func buckets(rows *core.SmartList[*school.School], name, field string) map[string]uint64 {
    list := need(rows.Facet(name)); result := map[string]uint64{}
    for _, row := range list.Data { result[need(row[field].TryText())] = need(row["count"].TryU64()) }
    return result
}
func load(context *runtime.UserContext, name string) *school.School {
    row, err := lib.Q.Schools().WithNameIs(name).Limit(2).
        Comment("Load complete School state for mutation").Purpose("Preserve optimistic version").ExecuteForOne(context)
    must(err); if row == nil { panic("School not found") }; return row
}
func main() {
    if len(os.Args) != 2 { panic("Expected one advanced phase") }
    phase := os.Args[1]
    switch phase { case "bootstrap", "transaction", "worker", "seed", "query", "update", "read-update", "delete", "read-delete": default: panic("Unknown phase") }
    context, err := lib.ServiceRuntimeFromEnv(); must(err); must(lib.EnsureSchema(context))
    if phase == "seed" {
        var fixture struct { Address string; EstablishedDate string; Schools []struct { Name string; Capacity int64; Active bool; Type string } }
        data, err := os.ReadFile(os.Getenv("SCHOOL_FIXTURE")); must(err); must(json.Unmarshal(data, &fixture))
        established, err := time.Parse("2006-01-02", fixture.EstablishedDate); must(err)
        for _, item := range fixture.Schools {
            row := lib.Q.Schools().Comment("Create an advanced School fixture row").Purpose("Seed advanced School scenarios").NewEntity(context)
            row.UpdatePlatformId(1)
            if item.Type == "PRIMARY" { row.UpdateSchoolTypeToPrimary() } else { row.UpdateSchoolTypeToSecondary() }
            row.UpdateName(item.Name); row.UpdateAddress(fixture.Address); row.UpdateEstablishedDate(established)
            row.UpdateStudentCapacity(item.Capacity); row.UpdateActive(item.Active)
            _, err := row.AuditAs("Seed the advanced School fixture").Save(context); must(err)
        }
    }

    // scenario: transaction-commit, transaction-rollback
    if phase == "transaction" {
        rollback := os.Getenv("SCHOOL_SCENARIO") == "transaction-rollback"
        root, err := lib.Q.Platforms().SelectSchoolListWith(lib.Q.Schools().WithNameIs("Riverside Primary School").Limit(2)).
            Limit(2).Comment("Load the Platform and School transaction graph").Purpose("Verify atomic graph writes").ExecuteForOne(context)
        must(err); child := root.SchoolList().Items()[0]
        if rollback { winner := load(context, "Riverside Primary School"); winner.UpdateStudentCapacity(801)
            _, err = winner.AuditAs("Advance School before the stale graph").Save(context); must(err) }
        root.UpdateName("Transactional Campus"); child.UpdateStudentCapacity(810)
        fmt.Println("SCHOOL_GRAPH_ATTEMPT")
        _, conflict := root.AuditAs("Revise Platform and School atomically").Save(context)
        if conflict != nil { text := strings.ToLower(conflict.Error()); if !rollback || !(strings.Contains(text, "version") || strings.Contains(text, "optimistic") || strings.Contains(text, "conflict") || strings.Contains(text, "stale")) { panic(conflict) } }
        report(os.Getenv("SCHOOL_SCENARIO"), map[string]any{"rejected": conflict != nil})
    }
    // scenario: concurrent-same, concurrent-distinct
    if phase == "worker" {
        target, worker, barrier := os.Getenv("SCHOOL_TARGET"), os.Getenv("SCHOOL_WORKER"), os.Getenv("SCHOOL_BARRIER")
        row := load(context, target); observedVersion := need(school.NewSchoolExpression(row).Version().Eval())
        ready, err := json.Marshal(map[string]any{"observedVersion": observedVersion}); must(err)
        must(os.WriteFile(barrier + "/" + worker + ".ready", ready, 0600))
        deadline := time.Now().Add(30 * time.Second)
        for { if _, err := os.Stat(barrier + "/release"); err == nil { break }; if time.Now().After(deadline) { panic("Barrier timeout") }; time.Sleep(10 * time.Millisecond) }
        capacity := int64(811); if worker == "b" { capacity = 822 }; row.UpdateStudentCapacity(capacity)
        _, conflict := row.AuditAs("Concurrent School capacity revision").Save(context); outcome, conflictReason := "committed", ""
        if conflict != nil { text := strings.ToLower(conflict.Error()); if !(strings.Contains(text, "version") || strings.Contains(text, "optimistic") || strings.Contains(text, "conflict") || strings.Contains(text, "stale")) { panic(conflict) }; outcome = "conflict"; conflictReason = conflict.Error() }
        data, err := json.Marshal(map[string]any{"worker": worker, "target": target, "observedVersion": observedVersion, "outcome": outcome, "conflictReason": conflictReason}); must(err)
        fmt.Println("SCHOOL_WORKER " + string(data))
    }

    if phase == "query" {
        // scenario: continuous-ascending
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "continuous-ascending" {
            pages := make([][]string, 0); plans := make([]string, 0)

            for _, step := range [][2]uint64{{0,0},{2,0},{4,0}} {
                page, err := lib.Q.SchoolsMinimal().SelectName().WithStudentCapacityGreaterThanOrEqualTo(int64(step[1])).
                    OrderByIdAsc().Offset(step[0]).Limit(2).OptimizeForContinuousPageFetchWith("continuous-ascending", 60).
                    Comment("Browse School pagination").Purpose("Verify continuous-ascending").ExecuteForList(context)
                must(err); pages = append(pages, names(page)); plans = append(plans, context.ContinuousPagePlan())

            }
            report("continuous-ascending", map[string]any{"pages": pages, "plans": plans})
        }
        // scenario: continuous-descending
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "continuous-descending" {
            pages := make([][]string, 0); plans := make([]string, 0)

            for _, step := range [][2]uint64{{0,0},{2,0},{4,0}} {
                page, err := lib.Q.SchoolsMinimal().SelectName().WithStudentCapacityGreaterThanOrEqualTo(int64(step[1])).
                    OrderByIdDesc().Offset(step[0]).Limit(2).OptimizeForContinuousPageFetchWith("continuous-descending", 60).
                    Comment("Browse School pagination").Purpose("Verify continuous-descending").ExecuteForList(context)
                must(err); pages = append(pages, names(page)); plans = append(plans, context.ContinuousPagePlan())

            }
            report("continuous-descending", map[string]any{"pages": pages, "plans": plans})
        }
        // scenario: continuous-cache-miss
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "continuous-cache-miss" {
            pages := make([][]string, 0); plans := make([]string, 0)

            for _, step := range [][2]uint64{{2,0},{4,0}} {
                page, err := lib.Q.SchoolsMinimal().SelectName().WithStudentCapacityGreaterThanOrEqualTo(int64(step[1])).
                    OrderByIdAsc().Offset(step[0]).Limit(2).OptimizeForContinuousPageFetchWith("continuous-cache-miss", 60).
                    Comment("Browse School pagination").Purpose("Verify continuous-cache-miss").ExecuteForList(context)
                must(err); pages = append(pages, names(page)); plans = append(plans, context.ContinuousPagePlan())

            }
            report("continuous-cache-miss", map[string]any{"pages": pages, "plans": plans})
        }
        // scenario: id-set-jump
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "id-set-jump" {
            pages := make([][]string, 0); plans := make([]string, 0)
            totals := make([]uint64, 0); observedCounts := make([]uint64, 0)
            for _, step := range [][2]uint64{{4,0},{0,0},{2,0},{6,0}} {
                page, err := lib.Q.SchoolsMinimal().SelectName().WithStudentCapacityGreaterThanOrEqualTo(int64(step[1])).
                    OrderByStudentCapacityDesc().OrderByNameAsc().OrderByIdAsc().Offset(step[0]).Limit(2).OptimizePaginationWithIDSetConfig("id-set-jump", 60, 100).Count().
                    Comment("Browse School pagination").Purpose("Verify id-set-jump").ExecuteForList(context)
                must(err); pages = append(pages, names(page)); plans = append(plans, context.IDSetPlan())
                totals = append(totals, *page.TotalCount); count, _ := context.IDSetCount(); observedCounts = append(observedCounts, count)
            }
            report("id-set-jump", map[string]any{"pages": pages, "plans": plans, "totals": totals, "observedCounts": observedCounts})
        }
        // scenario: id-set-empty
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "id-set-empty" {
            pages := make([][]string, 0); plans := make([]string, 0)
            totals := make([]uint64, 0); observedCounts := make([]uint64, 0)
            for _, step := range [][2]uint64{{0,100000},{2,100000}} {
                page, err := lib.Q.SchoolsMinimal().SelectName().WithStudentCapacityGreaterThanOrEqualTo(int64(step[1])).
                    OrderByStudentCapacityDesc().OrderByNameAsc().OrderByIdAsc().Offset(step[0]).Limit(2).OptimizePaginationWithIDSetConfig("id-set-empty", 60, 100).Count().
                    Comment("Browse School pagination").Purpose("Verify id-set-empty").ExecuteForList(context)
                must(err); pages = append(pages, names(page)); plans = append(plans, context.IDSetPlan())
                totals = append(totals, *page.TotalCount); count, _ := context.IDSetCount(); observedCounts = append(observedCounts, count)
            }
            report("id-set-empty", map[string]any{"pages": pages, "plans": plans, "totals": totals, "observedCounts": observedCounts})
        }
        // scenario: id-set-overflow
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "id-set-overflow" {
            pages := make([][]string, 0); plans := make([]string, 0)
            totals := make([]uint64, 0); observedCounts := make([]uint64, 0)
            for _, step := range [][2]uint64{{2,0}} {
                page, err := lib.Q.SchoolsMinimal().SelectName().WithStudentCapacityGreaterThanOrEqualTo(int64(step[1])).
                    OrderByStudentCapacityDesc().OrderByNameAsc().OrderByIdAsc().Offset(step[0]).Limit(2).OptimizePaginationWithIDSetConfig("id-set-overflow", 60, 3).Count().
                    Comment("Browse School pagination").Purpose("Verify id-set-overflow").ExecuteForList(context)
                must(err); pages = append(pages, names(page)); plans = append(plans, context.IDSetPlan())
                totals = append(totals, *page.TotalCount); count, _ := context.IDSetCount(); observedCounts = append(observedCounts, count)
            }
            report("id-set-overflow", map[string]any{"pages": pages, "plans": plans, "totals": totals, "observedCounts": observedCounts})
        }
        // scenario: id-set-isolation
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "id-set-isolation" {
            pages := make([][]string, 0); plans := make([]string, 0)
            totals := make([]uint64, 0); observedCounts := make([]uint64, 0)
            for _, step := range [][2]uint64{{0,500},{0,1000},{0,500}} {
                page, err := lib.Q.SchoolsMinimal().SelectName().WithStudentCapacityGreaterThanOrEqualTo(int64(step[1])).
                    OrderByStudentCapacityDesc().OrderByNameAsc().OrderByIdAsc().Offset(step[0]).Limit(2).OptimizePaginationWithIDSetConfig("id-set-isolation", 60, 100).Count().
                    Comment("Browse School pagination").Purpose("Verify id-set-isolation").ExecuteForList(context)
                must(err); pages = append(pages, names(page)); plans = append(plans, context.IDSetPlan())
                totals = append(totals, *page.TotalCount); count, _ := context.IDSetCount(); observedCounts = append(observedCounts, count)
            }
            report("id-set-isolation", map[string]any{"pages": pages, "plans": plans, "totals": totals, "observedCounts": observedCounts})
        }
        // scenario: pagination
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "pagination" {
        page, err := lib.Q.SchoolsMinimal().SelectName().WhichAreActive().WithStudentCapacityGreaterThanOrEqualTo(500).
            OrderByStudentCapacityDesc().OrderByIdAsc().Offset(1).Limit(2).Count().
            Comment("Page active schools by capacity").Purpose("Review the School directory").ExecuteForList(context)
        must(err); if page.TotalCount == nil { panic("Missing filtered total") }
        report("pagination", map[string]any{"names": names(page), "total": *page.TotalCount})
        }
        // scenario: relations
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "relations" {
        rows, err := lib.Q.SchoolsMinimal().SelectName().WithNameIs("Riverside Primary School").
            SelectSchoolTypeWith(lib.Q.SchoolTypesMinimal().SelectCode()).
            SelectPlatformWith(lib.Q.PlatformsMinimal().SelectName()).Limit(2).
            Comment("Load School type and platform").Purpose("Review loaded School relations").ExecuteForList(context)
        must(err); if len(rows.Data) != 1 { panic("Expected one School") }
        expression := school.NewSchoolExpression(rows.Data[0])
        report("relations", map[string]any{"school": need(expression.Name().Eval()), "type": need(expression.SchoolType().Code().Eval()), "platform": need(expression.Platform().Name().Eval())})
        }
        // scenario: groups
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "groups" {
        groups, err := lib.Q.Schools().GroupBySchoolType().CountAs("count").SumStudentCapacityAs("total").AvgStudentCapacityAs("average").Limit(10).
            Comment("Group School capacity by type").Purpose("Verify provider aggregation").ExecuteRecords(context)
        must(err); distribution := []map[string]any{}
        for _, row := range groups { distribution = append(distribution, map[string]any{"type": need(row["school_type"].TryU64()),
            "count": need(row["count"].TryU64()), "total": need(row["total"].TryF64()), "average": need(row["average"].TryF64())}) }
        report("groups", distribution)
        }
        // scenario: relation-metrics
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "relation-metrics" {
        cards, err := lib.Q.SchoolTypesMinimal().SelectCode().CountSchoolsAs("count").
            SumStudentCapacityOfSchoolsAs("total", lib.Q.Schools()).OrderByCodeAsc().Limit(10).
            Comment("Calculate SchoolType relation metrics").Purpose("Verify provider relation aggregation").ExecuteRecords(context)
        must(err); metrics := map[string]any{}
        for _, row := range cards { metrics[need(row["code"].TryText())] = map[string]any{"count": need(row["count"].TryU64()), "total": need(row["total"].TryF64())} }
        report("relation-metrics", metrics)
        }
        // scenario: facets
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "facets" {
        facets := func(includeAll bool) *core.SmartList[*school.School] {
            rows, err := lib.Q.SchoolsMinimal().SelectName().WithNameIs("Riverside Primary School").
                FacetBySchoolTypeAs("types", lib.Q.SchoolTypesMinimal().SelectCode().CountSchoolsAs("count"), includeAll).
                FacetByPlatformAs("platforms", lib.Q.PlatformsMinimal().SelectName().CountSchoolsAs("count"), false).
                OrderByIdAsc().Limit(2).Comment("Facet the matching School set").Purpose("Compare zero and matched buckets").ExecuteForList(context)
            must(err); return rows
        }
        allRows, matched := facets(true), facets(false)
        report("facets", map[string]any{"includeAll": buckets(allRows, "types", "code"), "matchedOnly": buckets(matched, "types", "code"), "platforms": buckets(allRows, "platforms", "name"), "rows": names(allRows)})
        }
        // scenario: page-boundaries
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "page-boundaries" {
            pages := [][]string{}; totals := []uint64{}
            for _, offset := range []uint64{0, 2, 4, 6} {
                page, err := lib.Q.SchoolsMinimal().SelectName().
                    OrderByStudentCapacityDesc().OrderByNameAsc().OrderByIdAsc().Offset(offset).Limit(2).Count().
                    Comment("Traverse School pages including an empty tail").Purpose("Verify stable page boundaries").ExecuteForList(context)
                must(err); if page.TotalCount == nil { panic("Missing filtered total") }
                pages = append(pages, names(page)); totals = append(totals, *page.TotalCount)
            }
            report("page-boundaries", map[string]any{"pages": pages, "totals": totals})
        }
        // scenario: relation-predicates
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "relation-predicates" {
            matching, err := lib.Q.SchoolsMinimal().SelectName().
                WithSchoolTypeMatching(lib.Q.SchoolTypesMinimal().WithCodeIs("PRIMARY")).
                OrderByNameAsc().Limit(10).Comment("Match School type by child request").
                Purpose("Verify relation predicate semantics").ExecuteForList(context)
            must(err)
            excluding, err := lib.Q.SchoolsMinimal().SelectName().
                WithoutSchoolTypeMatching(lib.Q.SchoolTypesMinimal().WithCodeIs("PRIMARY")).
                OrderByNameAsc().Limit(10).Comment("Exclude School type by child request").
                Purpose("Verify negative relation predicates").ExecuteForList(context)
            must(err)
            nested, err := lib.Q.SchoolsMinimal().SelectName().
                WithSchoolTypeMatching(lib.Q.SchoolTypesMinimal().WithCodeIs("PRIMARY").
                    WithPlatformMatching(lib.Q.PlatformsMinimal().WithNameIs("Campus Learning Platform"))).
                OrderByNameAsc().Limit(10).Comment("Match School through type and platform").
                Purpose("Verify two-level relation predicates").ExecuteForList(context)
            must(err)
            report("relation-predicates", map[string]any{"matching": names(matching), "excluding": names(excluding), "nested": names(nested)})
        }
        // scenario: blank-intent
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "blank-intent" {
            rejected := []bool{}
            for _, intent := range [][2]string{{" ", "Verify blank comment rejection"}, {"Check blank purpose rejection", " "}} {
                denied := func() (denied bool) {
                    check := func(failure any) bool {
                        message := strings.ToLower(fmt.Sprint(failure))
                        if !strings.Contains(message, "comment") && !strings.Contains(message, "purpose") && !strings.Contains(message, "intent") { panic(failure) }
                        return true
                    }
                    defer func() { if failure := recover(); failure != nil { denied = check(failure) } }()
                    _, err := lib.Q.SchoolsMinimal().Limit(1).Comment(intent[0]).Purpose(intent[1]).ExecuteForList(context)
                    if err != nil { return check(err) }; return false
                }()
                rejected = append(rejected, denied)
            }
            report("blank-intent", map[string]any{"blankComment": rejected[0], "blankPurpose": rejected[1]})
        }
        // scenario: empty-page
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "empty-page" {
        page, err := lib.Q.SchoolsMinimal().SelectName().WithNameIs("No such School").
            OrderByStudentCapacityDesc().OrderByIdAsc().Offset(1).Limit(2).Count().
            Comment("Read a School filter with no matches").Purpose("Verify empty page count").ExecuteForList(context)
        must(err); if page.TotalCount == nil { panic("Missing filtered total") }
        report("empty-page", map[string]any{"names": names(page), "total": *page.TotalCount})
        }
        // scenario: filtered-groups
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "filtered-groups" {
        groups, err := lib.Q.Schools().WhichAreActive().WithStudentCapacityGreaterThanOrEqualTo(500).GroupBySchoolType().CountAs("count").SumStudentCapacityAs("total").AvgStudentCapacityAs("average").Limit(10).
            Comment("Aggregate active Schools with capacity at least 500").Purpose("Verify provider aggregation").ExecuteRecords(context)
        must(err); distribution := []map[string]any{}
        for _, row := range groups { distribution = append(distribution, map[string]any{"type": need(row["school_type"].TryU64()),
            "count": need(row["count"].TryU64()), "total": need(row["total"].TryF64()), "average": need(row["average"].TryF64())}) }
        report("filtered-groups", distribution)
        }
        // scenario: filtered-children
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "filtered-children" {
        types, err := lib.Q.SchoolTypesMinimal().SelectCode().
            SelectSchoolListWith(lib.Q.SchoolsMinimal().SelectName().WhichAreNotActive().OrderByStudentCapacityDesc().OrderByIdAsc().Limit(2)).
            OrderByCodeAsc().Limit(10).Comment("Load inactive Schools for each type").Purpose("Preserve parents with empty child lists").ExecuteForList(context)
        must(err); top := map[string][]string{}
        for _, row := range types.Data {
            expression := school_type.NewSchoolTypeExpression(row); children := []string{}
            for i := 0; i < need(expression.SchoolList().Size().Eval()); i++ { children = append(children, need(expression.SchoolList().Get(i).Name().Eval())) }
            top[need(expression.Code().Eval())] = children
        }
        report("filtered-children", top)
        }
        // scenario: empty-facets
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "empty-facets" {
        facets := func(includeAll bool) *core.SmartList[*school.School] {
            rows, err := lib.Q.SchoolsMinimal().SelectName().WithNameIs("No such School").
                FacetBySchoolTypeAs("types", lib.Q.SchoolTypesMinimal().SelectCode().CountSchoolsAs("count"), includeAll).
                FacetByPlatformAs("platforms", lib.Q.PlatformsMinimal().SelectName().CountSchoolsAs("count"), false).
                OrderByIdAsc().Limit(2).Comment("Facet the matching School set").Purpose("Compare zero and matched buckets").ExecuteForList(context)
            must(err); return rows
        }
        allRows, matched := facets(true), facets(false)
        report("empty-facets", map[string]any{"includeAll": buckets(allRows, "types", "code"), "matchedOnly": buckets(matched, "types", "code"), "platforms": buckets(allRows, "platforms", "name"), "rows": names(allRows)})
        }
        // scenario: top-n
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "top-n" {
        types, err := lib.Q.SchoolTypesMinimal().SelectCode().
            SelectSchoolListWith(lib.Q.SchoolsMinimal().SelectName().OrderByStudentCapacityDesc().OrderByIdAsc().Limit(2)).
            OrderByCodeAsc().Limit(10).Comment("Load the two largest schools for each type").Purpose("Verify Top-N across two parents").ExecuteForList(context)
        must(err); top := map[string][]string{}
        for _, row := range types.Data {
            expression := school_type.NewSchoolTypeExpression(row); children := []string{}
            for i := 0; i < need(expression.SchoolList().Size().Eval()); i++ { children = append(children, need(expression.SchoolList().Get(i).Name().Eval())) }
            top[need(expression.Code().Eval())] = children
        }
        report("top-n", top)
        }
    }
    // scenario: update
    if phase == "update" {
        row, stale := load(context, "Riverside Primary School"), load(context, "Riverside Primary School")
        before := need(school.NewSchoolExpression(row).Version().Eval()); row.UpdateStudentCapacity(950)
        row, err = row.AuditAs("Approve School capacity revision").Save(context); must(err)
        report("update", map[string]any{"before": before, "after": need(school.NewSchoolExpression(row).Version().Eval()), "capacity": need(school.NewSchoolExpression(row).StudentCapacity().Eval())})
        stale.UpdateStudentCapacity(999); _, conflict := stale.AuditAs("Reject stale School capacity revision").Save(context)
        rejected := false
        if conflict != nil {
            text := strings.ToLower(conflict.Error())
            for _, word := range []string{"version", "optimistic", "conflict", "stale"} { rejected = rejected || strings.Contains(text, word) }
            if !rejected { panic(conflict) }
        }
        report("stale-write", map[string]any{"rejected": rejected})
    }
    if phase == "read-update" {
        row := load(context, "Riverside Primary School"); expression := school.NewSchoolExpression(row)
        report("read-update", map[string]any{"capacity": need(expression.StudentCapacity().Eval()), "version": need(expression.Version().Eval())})
    }
    // scenario: delete
    if phase == "delete" { row := load(context, "Hill Secondary School"); row.MarkForDeletion(); _, err := row.AuditAs("Retire inactive School fixture").Save(context); must(err) }
    if phase == "delete" || (phase == "read-delete" && (os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "read-delete")) {
        rows, err := lib.Q.SchoolsMinimal().WithNameIs("Hill Secondary School").Limit(2).
            Comment("Check the retired School is hidden").Purpose("Verify soft deletion visibility").ExecuteForList(context)
        must(err); value := map[string]any{"visible": len(rows.Data)}
        if phase == "read-delete" {
            deleted, err := lib.Q.SchoolsMinimal().DeletedRowsOnly().WithNameIs("Hill Secondary School").Limit(2).
                Comment("Read the School tombstone").Purpose("Verify persisted deletion intent").ExecuteForList(context)
            must(err); value["deleted"] = len(deleted.Data)
        }
        report(phase, value)
    }
    if phase == "read-delete" {
        // scenario: deleted-groups
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "deleted-groups" {
        groups, err := lib.Q.Schools().GroupBySchoolType().CountAs("count").SumStudentCapacityAs("total").AvgStudentCapacityAs("average").Limit(10).
            Comment("Aggregate surviving Schools after deletion").Purpose("Verify provider aggregation").ExecuteRecords(context)
        must(err); distribution := []map[string]any{}
        for _, row := range groups { distribution = append(distribution, map[string]any{"type": need(row["school_type"].TryU64()),
            "count": need(row["count"].TryU64()), "total": need(row["total"].TryF64()), "average": need(row["average"].TryF64())}) }
        report("deleted-groups", distribution)
        }
        // scenario: deleted-metrics
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "deleted-metrics" {
        cards, err := lib.Q.SchoolTypesMinimal().SelectCode().CountSchoolsAs("count").
            SumStudentCapacityOfSchoolsAs("total", lib.Q.Schools()).OrderByCodeAsc().Limit(10).
            Comment("Calculate relation metrics after School deletion").Purpose("Verify provider relation aggregation").ExecuteRecords(context)
        must(err); metrics := map[string]any{}
        for _, row := range cards { metrics[need(row["code"].TryText())] = map[string]any{"count": need(row["count"].TryU64()), "total": need(row["total"].TryF64())} }
        report("deleted-metrics", metrics)
        }
        // scenario: deleted-facets
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "deleted-facets" {
        facets := func(includeAll bool) *core.SmartList[*school.School] {
            rows, err := lib.Q.SchoolsMinimal().SelectName().
                FacetBySchoolTypeAs("types", lib.Q.SchoolTypesMinimal().SelectCode().CountSchoolsAs("count"), includeAll).
                FacetByPlatformAs("platforms", lib.Q.PlatformsMinimal().SelectName().CountSchoolsAs("count"), false).
                OrderByStudentCapacityDesc().OrderByIdAsc().Limit(2).Comment("Facet the matching School set").Purpose("Compare zero and matched buckets").ExecuteForList(context)
            must(err); return rows
        }
        allRows, matched := facets(true), facets(false)
        report("deleted-facets", map[string]any{"includeAll": buckets(allRows, "types", "code"), "matchedOnly": buckets(matched, "types", "code"), "platforms": buckets(allRows, "platforms", "name"), "rows": names(allRows)})
        }
        // scenario: deleted-children
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "deleted-children" {
        types, err := lib.Q.SchoolTypesMinimal().SelectCode().
            SelectSchoolListWith(lib.Q.SchoolsMinimal().SelectName().OrderByStudentCapacityDesc().OrderByIdAsc().Limit(2)).
            OrderByCodeAsc().Limit(10).Comment("Load surviving Schools for each type").Purpose("Exclude tombstones from ordinary child lists").ExecuteForList(context)
        must(err); top := map[string][]string{}
        for _, row := range types.Data {
            expression := school_type.NewSchoolTypeExpression(row); children := []string{}
            for i := 0; i < need(expression.SchoolList().Size().Eval()); i++ { children = append(children, need(expression.SchoolList().Get(i).Name().Eval())) }
            top[need(expression.Code().Eval())] = children
        }
        report("deleted-children", top)
        }
        // scenario: deleted-child-tombstones
        if os.Getenv("SCHOOL_SCENARIO") == "" || os.Getenv("SCHOOL_SCENARIO") == "deleted-child-tombstones" {
        types, err := lib.Q.SchoolTypesMinimal().SelectCode().
            SelectSchoolListWith(lib.Q.SchoolsMinimal().SelectName().DeletedRowsOnly().OrderByStudentCapacityDesc().OrderByIdAsc().Limit(2)).
            OrderByCodeAsc().Limit(10).Comment("Load retired Schools for each live type").Purpose("Keep child deletion scope separate from parent visibility").ExecuteForList(context)
        must(err); top := map[string][]string{}
        for _, row := range types.Data {
            expression := school_type.NewSchoolTypeExpression(row); children := []string{}
            for i := 0; i < need(expression.SchoolList().Size().Eval()); i++ { children = append(children, need(expression.SchoolList().Get(i).Name().Eval())) }
            top[need(expression.Code().Eval())] = children
        }
        report("deleted-child-tombstones", top)
        }
    }
    fmt.Printf("SCHOOL_OK phase=%s\n", phase)
}
