// route_proof.el — PROVES decorate -> serve in El. Each handler is DECORATED
// with its route AND its VBD role (stacked: @route(...) @accessor|@manager fn).
// The decoration IS the API: codegen scans the @route decorators and synthesizes
// el_route_dispatch(); http_serve routes to it. No hand-written 90-branch dispatch.
//
// This standalone service proves the SEAM (route+serve). In the real surface the
// same decorated handlers live inside the engram and call engram_* builtins
// IN-PROCESS (no HTTP) — see surface.el.
//
// Build: elc-route route_proof.el > route_proof.c ; cc ... ; run on a sandbox port.

// query-stripped path (the dispatcher matches on this).
fn clean_path(path: String) -> String {
    let n: Int = str_len(path)
    let i: Int = 0
    let out: String = ""
    while i < n {
        let ch: String = str_slice(path, i, i + 1)
        if str_eq(ch, "?") { return out }
        let out = out + ch
        let i = i + 1
    }
    return out
}

// ── the reshaped surface as DECORATED handlers (route + VBD role) ─────────────

@route("/read", "GET")
@accessor
fn h_read(method: String, path: String, body: String) -> String {
    return "{\"op\":\"read\",\"role\":\"accessor\",\"vantage-read\":\"bounded-slice\",\"served-by\":\"@route decoration\"}"
}

@route("/write", "POST")
@accessor
fn h_write(method: String, path: String, body: String) -> String {
    return "{\"op\":\"write\",\"role\":\"accessor\",\"served-by\":\"@route decoration\"}"
}

@route("/relate", "POST")
@accessor
fn h_relate(method: String, path: String, body: String) -> String {
    return "{\"op\":\"relate\",\"role\":\"accessor\"}"
}

@route("/supersede", "POST")
@accessor
fn h_supersede(method: String, path: String, body: String) -> String {
    return "{\"op\":\"supersede\",\"role\":\"accessor\",\"immutable\":true}"
}

@route("/think", "GET")
@manager
fn h_think(method: String, path: String, body: String) -> String {
    return "{\"op\":\"think\",\"role\":\"manager\",\"one-operation\":true}"
}

@route("/attend", "POST")
@manager
fn h_attend(method: String, path: String, body: String) -> String {
    return "{\"op\":\"attend\",\"role\":\"manager\"}"
}

@route("/learn", "POST")
@manager
fn h_learn(method: String, path: String, body: String) -> String {
    return "{\"op\":\"learn\",\"role\":\"manager\",\"correspondence-beat\":true}"
}

// ── http_serve handler: call the GENERATED dispatcher; mixed-mode fallthrough ──
fn dispatch(method: String, path: String, body: String) -> String {
    let clean: String = clean_path(path)
    let r: String = el_route_dispatch(method, clean, path, body)
    if str_eq(r, "__EL_NO_ROUTE__") {
        return "{\"error\":\"no route\",\"path\":\"" + clean + "\"}"
    }
    return r
}

fn main() -> Int {
    let port: Int = parse_int(env("ROUTE_PROOF_PORT"), 8951)
    println("[route_proof] decorate->serve on :" + int_to_str(port))
    http_serve(port, "dispatch")
    return 0
}
