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96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
"""
Budget Router — Gradio Visualization Dashboard
Run: python app_gradio.py  (launches on http://localhost:7860)
"""
from __future__ import annotations

import math
import time
from typing import Dict, Optional, Tuple

import gradio as gr
from budget_router.environment import BudgetRouterEnv
from budget_router.models import Action, ActionType
from budget_router.tasks import TASK_PRESETS

from gradio_ui.config import MAX_STEPS as _MAX_STEPS, POLICY_CHOICES, SCENARIOS
from gradio_ui.policies import get_policy_runner
from gradio_ui.renderers import (
    _kpi_grid,
    render_incident_timeline,
    render_side_panel,
    render_grader_plot,
    MISSION_SCORE_HELP,
    MISSION_SCORE_LABEL,
    _GRADER_PENDING,
    _PROVIDER_EMPTY,
    render_history_table_compare,
)
from gradio_ui.state import fresh_side_state, _observation_to_dict, record_step
from gradio_ui.theme import LIGHT_CSS, THEME

MAX_STEPS = _MAX_STEPS


# Compatibility: preserve module-level MAX_STEPS for callers.

# ─── UI Build ─────────────────────────────────────────────────────────────────

def build_app() -> gr.Blocks:

    def _normalize_seed(seed: object, default: int = 42) -> int:
        if seed is None:
            return default
        try:
            val = float(seed)  # type: ignore[arg-type]
        except Exception:
            return default
        if math.isnan(val) or math.isinf(val):
            return default
        try:
            return int(val)
        except Exception:
            return default

    with gr.Blocks(title="Budget Router — Policy Comparison", theme=THEME, css=LIGHT_CSS) as demo:

        left_state = gr.State(fresh_side_state())
        right_state = gr.State(fresh_side_state())
        run_state = gr.State({"running": False, "scenario": "easy", "seed": 42, "step": 0})

        gr.Markdown(
            "# Budget Router — Policy Comparison\n"
            "_Select 2 policies · start episode · step or finish episode · compare outcomes_"
        )

        with gr.Row():
            with gr.Column(scale=1):
                left_title = gr.Markdown("## Policy A")
                left_policy = gr.Dropdown(choices=POLICY_CHOICES, value=None, label="Select policy")
                left_status = gr.Textbox(label="Status", interactive=False, lines=2)
                left_providers = gr.HTML(_PROVIDER_EMPTY())
                left_budget = gr.HTML("")
                left_kpis = gr.HTML(
                    _kpi_grid(
                        [
                            ("Step", "—"),
                            ("Last action", "—"),
                            ("Latency (ms)", "—"),
                            ("Budget remaining", "—"),
                            ("Reward", "—"),
                            ("Adaptation", "—"),
                        ]
                    )
                )
                left_badges = gr.HTML("")
                left_summary = gr.HTML(
                    _kpi_grid(
                        [
                            ("Failed %", "—"),
                            ("SLA breach %", "—"),
                            ("Avg latency (ms)", "—"),
                        ]
                    )
                )

            with gr.Column(scale=1):
                right_title = gr.Markdown("## Policy B")
                right_policy = gr.Dropdown(choices=POLICY_CHOICES, value=None, label="Select policy")
                right_status = gr.Textbox(label="Status", interactive=False, lines=2)
                right_providers = gr.HTML(_PROVIDER_EMPTY())
                right_budget = gr.HTML("")
                right_kpis = gr.HTML(
                    _kpi_grid(
                        [
                            ("Step", "—"),
                            ("Last action", "—"),
                            ("Latency (ms)", "—"),
                            ("Budget remaining", "—"),
                            ("Reward", "—"),
                            ("Adaptation", "—"),
                        ]
                    )
                )
                right_badges = gr.HTML("")
                right_summary = gr.HTML(
                    _kpi_grid(
                        [
                            ("Failed %", "—"),
                            ("SLA breach %", "—"),
                            ("Avg latency (ms)", "—"),
                        ]
                    )
                )

        with gr.Row():
            with gr.Column(scale=2):
                gr.Markdown("### Episode Controls")
                scenario_sel = gr.Radio(SCENARIOS, value="easy", label="Scenario")
                seed_inp = gr.Number(value=42, label="Seed", precision=0)
                start_btn = gr.Button("▶ Start Episode", variant="primary", interactive=False)
                with gr.Row():
                    step_btn = gr.Button("→ Step", variant="secondary", interactive=False)
                    fast_btn = gr.Button("⚡ Fast-forward", interactive=False)
                    finish_btn = gr.Button("⏩ Finish Episode", interactive=False)

        gr.Markdown(f"### {MISSION_SCORE_LABEL} (comparison)\n_{MISSION_SCORE_HELP}_")
        grader_plot = gr.Plot()

        with gr.Row(elem_classes=["episode-history-row"]):
            with gr.Column(scale=1):
                left_history_title = gr.Markdown("### Step History — Policy A")
                left_history_tbl = gr.HTML(render_history_table_compare([]), elem_classes=["episode-history-table"])
            with gr.Column(scale=1):
                right_history_title = gr.Markdown("### Step History — Policy B")
                right_history_tbl = gr.HTML(render_history_table_compare([]), elem_classes=["episode-history-table"])

        with gr.Row():
            with gr.Column(scale=1):
                left_grade_title = gr.Markdown(f"### {MISSION_SCORE_LABEL} — Policy A")
                left_grade = gr.HTML(_GRADER_PENDING())
            with gr.Column(scale=1):
                right_grade_title = gr.Markdown(f"### {MISSION_SCORE_LABEL} — Policy B")
                right_grade = gr.HTML(_GRADER_PENDING())

        gr.Markdown("### Incident Timeline")
        incidents_html = gr.HTML(render_incident_timeline("easy"))

        def _render_side(side: Dict, run: Dict, scenario_name: str) -> Tuple[str, str, str, str, str, str, str, str]:
            return render_side_panel(side, run, scenario_name)

        def _render_all(ls: Dict, rs: Dict, run: Dict) -> tuple:
            scenario_name = str(run.get("scenario", "easy") or "easy")
            l_out = _render_side(ls, run, scenario_name)
            r_out = _render_side(rs, run, scenario_name)
            plot = render_grader_plot(
                ls.get("history", []) or [],
                rs.get("history", []) or [],
                left_name=str(ls.get("policy_name") or ""),
                right_name=str(rs.get("policy_name") or ""),
            )
            incidents = render_incident_timeline(scenario_name)

            running = bool(run.get("running", False))
            btn_update = gr.update(interactive=running)
            config_update = gr.update(interactive=(not running))
            return (
                ls,
                rs,
                run,
                l_out[0],
                l_out[1],
                l_out[2],
                l_out[3],
                l_out[4],
                l_out[5],
                r_out[0],
                r_out[1],
                r_out[2],
                r_out[3],
                r_out[4],
                r_out[5],
                l_out[6],
                r_out[6],
                l_out[7],
                r_out[7],
                plot,
                incidents,
                config_update,
                config_update,
                config_update,
                config_update,
                config_update,
                btn_update,
                btn_update,
                btn_update,
            )

        OUTPUTS = [
            left_state,
            right_state,
            run_state,
            left_status,
            left_providers,
            left_budget,
            left_kpis,
            left_badges,
            left_summary,
            right_status,
            right_providers,
            right_budget,
            right_kpis,
            right_badges,
            right_summary,
            left_history_tbl,
            right_history_tbl,
            left_grade,
            right_grade,
            grader_plot,
            incidents_html,
            left_policy,
            right_policy,
            scenario_sel,
            seed_inp,
            start_btn,
            step_btn,
            fast_btn,
            finish_btn,
        ]

        GRADER_PLOT_IDX = OUTPUTS.index(grader_plot)

        def _update_start_enabled(p1: Optional[str], p2: Optional[str], run: Dict):
            left_name = str(p1 or "Policy A")
            right_name = str(p2 or "Policy B")
            running = bool((run or {}).get("running", False))
            ok = (bool(p1) and bool(p2)) and (not running)
            return (
                gr.update(interactive=ok),
                f"## {left_name}",
                f"## {right_name}",
                f"### Step History — {left_name}",
                f"### Step History — {right_name}",
                f"### {MISSION_SCORE_LABEL}{left_name}",
                f"### {MISSION_SCORE_LABEL}{right_name}",
            )

        left_policy.change(
            _update_start_enabled,
            inputs=[left_policy, right_policy, run_state],
            outputs=[start_btn, left_title, right_title, left_history_title, right_history_title, left_grade_title, right_grade_title],
        )
        right_policy.change(
            _update_start_enabled,
            inputs=[left_policy, right_policy, run_state],
            outputs=[start_btn, left_title, right_title, left_history_title, right_history_title, left_grade_title, right_grade_title],
        )

        scenario_sel.change(lambda s: render_incident_timeline(s), inputs=[scenario_sel], outputs=[incidents_html])

        def do_start(p1: str, p2: str, scenario: str, seed: Optional[float], _ls: Dict, _rs: Dict, _run: Dict):
            ls = fresh_side_state()
            rs = fresh_side_state()

            seed_int = _normalize_seed(seed, default=42)

            if not p1 or not p2:
                run = {"running": False, "scenario": scenario, "seed": seed_int, "step": 0}
                ls["status"] = "Select both policies to start."
                rs["status"] = "Select both policies to start."
                return _render_all(ls, rs, run)

            runner_l, err_l = get_policy_runner(p1)
            runner_r, err_r = get_policy_runner(p2)
            if err_l or err_r or runner_l is None or runner_r is None:
                ls["status"] = f"❌ {err_l}" if err_l else ""
                rs["status"] = f"❌ {err_r}" if err_r else ""
                run = {"running": False, "scenario": scenario, "seed": seed_int, "step": 0}
                return _render_all(ls, rs, run)

            env_l = BudgetRouterEnv()
            env_r = BudgetRouterEnv()
            obs_l = env_l.reset(seed=seed_int, scenario=scenario)
            obs_r = env_r.reset(seed=seed_int, scenario=scenario)
            try:
                runner_l.reset(scenario)
            except Exception:
                pass
            try:
                runner_r.reset(scenario)
            except Exception:
                pass

            ls.update(
                {
                    "env": env_l,
                    "policy_name": p1,
                    "policy_runner": runner_l,
                    "obs": _observation_to_dict(obs_l),
                    "status": f"✅ Running · {p1}",
                }
            )
            rs.update(
                {
                    "env": env_r,
                    "policy_name": p2,
                    "policy_runner": runner_r,
                    "obs": _observation_to_dict(obs_r),
                    "status": f"✅ Running · {p2}",
                }
            )
            run = {"running": True, "scenario": scenario, "seed": seed_int, "step": 0}
            return _render_all(ls, rs, run)

        def _apply_local_step(side: Dict, scenario_name: str, global_step: int) -> Dict:
            if side.get("done"):
                return side
            env = side.get("env")
            runner = side.get("policy_runner")
            if env is None or runner is None:
                side["done"] = True
                side["status"] = "❌ Not initialized"
                return side
            try:
                action_str = runner.choose_action(side.get("obs", {}) or {})
            except Exception as exc:
                side["done"] = True
                side["status"] = f"❌ Policy error: {exc}"
                return side

            pre_obs = dict(side.get("obs", {}) or {})
            obs_obj = env.step(Action(action_type=ActionType(action_str)))
            obs = _observation_to_dict(obs_obj)
            reward = float(obs.get("reward", 0.0) or 0.0)
            meta = dict(obs.get("metadata", {}) or {})
            done = bool(obs.get("done", False))
            side["history"].append(record_step(global_step, action_str, obs, reward, meta, health_obs=pre_obs))
            side["obs"] = obs
            side["cumulative_reward"] = float(side.get("cumulative_reward", 0.0) or 0.0) + reward
            side["done"] = done
            side["status"] = "✅ Done" if done else str(side.get("status", ""))
            return side

        def do_step(ls: Dict, rs: Dict, run: Dict):
            if not bool(run.get("running", False)):
                return _render_all(ls, rs, run)
            if int(run.get("step", 0) or 0) >= MAX_STEPS:
                run["running"] = False
                return _render_all(ls, rs, run)

            next_step = int(run.get("step", 0) or 0) + 1
            scenario = str(run.get("scenario", "easy") or "easy")

            ls = _apply_local_step(ls, scenario, next_step)
            rs = _apply_local_step(rs, scenario, next_step)
            run["step"] = next_step

            if next_step >= MAX_STEPS or (ls.get("done") and rs.get("done")):
                run["running"] = False
            return _render_all(ls, rs, run)

        def _stream_to_end(ls: Dict, rs: Dict, run: Dict):
            if not bool(run.get("running", False)):
                yield _render_all(ls, rs, run)
                return

            frozen = _render_all(ls, rs, run)
            frozen_grader_plot = frozen[GRADER_PLOT_IDX]

            while bool(run.get("running", False)) and int(run.get("step", 0) or 0) < MAX_STEPS:
                out = do_step(ls, rs, run)
                ls, rs, run = out[0], out[1], out[2]
                out_list = list(out)
                out_list[GRADER_PLOT_IDX] = frozen_grader_plot
                yield tuple(out_list)
                time.sleep(0.12)
                if not bool(run.get("running", False)):
                    break

            yield _render_all(ls, rs, run)

        def do_fast_forward(ls: Dict, rs: Dict, run: Dict):
            yield from _stream_to_end(ls, rs, run)

        def do_finish(ls: Dict, rs: Dict, run: Dict):
            yield from _stream_to_end(ls, rs, run)

        start_btn.click(do_start, inputs=[left_policy, right_policy, scenario_sel, seed_inp, left_state, right_state, run_state], outputs=OUTPUTS)
        step_btn.click(do_step, inputs=[left_state, right_state, run_state], outputs=OUTPUTS)
        fast_btn.click(do_fast_forward, inputs=[left_state, right_state, run_state], outputs=OUTPUTS)
        finish_btn.click(do_finish, inputs=[left_state, right_state, run_state], outputs=OUTPUTS)

    return demo


if __name__ == "__main__":
    app = build_app()
    app.queue()
    app.launch(server_port=7860)