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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#!/usr/bin/env python3
"""Local runner CLI.

Runs Playwright locally but persists results to a cloud backend (FastAPI + Supabase).
This keeps secrets (OpenAI key, DB password, Supabase service role) server-side.
"""

from __future__ import annotations

import json
import mimetypes
import os
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional

import httpx
import typer
from rich.console import Console

from src.core.ai_client import AIClient, get_effective_session_prompt
from src.core.rag_evaluator import RAGEvaluator
from src.core.test_engine import TestEngine
from src.core.tone_evaluator import ToneEvaluator
from src.core.turn_evaluator import TurnEvaluator
from src.models import Bot, Persona, Scenario, TestResult, TestSession
from src.utils.env import env_bool

app = typer.Typer(help="Run test sessions locally and push results to the cloud backend.")
console = Console()


def _normalize_backend_url(url: str) -> str:
    url = (url or "").strip()
    if not url:
        raise typer.BadParameter("Missing backend URL")
    if not url.startswith("http://") and not url.startswith("https://"):
        url = "https://" + url
    return url.rstrip("/")


def _auth_headers(token: str) -> Dict[str, str]:
    token = (token or "").strip()
    if not token:
        raise typer.BadParameter("Missing auth token (Supabase access_token)")
    return {"Authorization": f"Bearer {token}"}


def _build_models(payload: dict) -> tuple[TestSession, Bot, List[Scenario], List[Persona], List[dict]]:
    session = TestSession(**(payload.get("session") or {}))
    bot = Bot(**(payload.get("bot") or {}))

    scenarios = [Scenario(**s) for s in (payload.get("scenarios") or [])]
    personas = [Persona(**p) for p in (payload.get("personas") or [])]
    links = payload.get("links") or []
    if not isinstance(links, list):
        links = []

    return session, bot, scenarios, personas, links


def _group_by_persona(
    scenarios: List[Scenario],
    personas: List[Persona],
    links: List[dict],
) -> Dict[str, dict]:
    scenarios_by_id = {str(s.id): s for s in scenarios}
    personas_by_id = {str(p.id): p for p in personas}

    groups: Dict[str, dict] = {}
    seen = set()
    for link in links:
        scenario_id = str(link.get("scenario_id") or "")
        persona_id = str(link.get("persona_id") or "")
        if not scenario_id or not persona_id:
            continue
        key = (scenario_id, persona_id)
        if key in seen:
            continue
        seen.add(key)

        scenario = scenarios_by_id.get(scenario_id)
        persona = personas_by_id.get(persona_id)
        if not scenario or not persona:
            continue

        groups.setdefault(persona_id, {"persona": persona, "scenarios": []})["scenarios"].append(scenario)

    return groups


def _scenario_goal_text(scenario: Scenario) -> str:
    description = str(getattr(scenario, "description", "") or "").strip()
    if description:
        return description
    success_criteria = getattr(scenario, "success_criteria", None)
    expected_intent = (
        str(getattr(success_criteria, "expected_intent", "") or "").strip()
        if success_criteria
        else ""
    )
    if expected_intent:
        return expected_intent
    return f"Complete scenario '{scenario.name}'."


def _build_group_prompt(persona: Persona, scenarios: List[Scenario]) -> str:
    overview = []
    for idx, scenario in enumerate(list(scenarios or [])[:12], start=1):
        overview.append(f"{idx}. {scenario.name}: {_scenario_goal_text(scenario)}")
    if len(scenarios or []) > 12:
        overview.append(f"... plus {len(scenarios) - 12} additional scenario(s) in this run.")
    return AIClient.build_persona_system_prompt(persona=persona, scenario_overview=overview)


def _upload_screenshot(
    client: httpx.Client,
    session_id: str,
    *,
    path: str,
    result_id: str,
    label: str,
) -> Optional[str]:
    p = Path(path)
    if not p.exists() or not p.is_file():
        return None

    # Live preview is overwritten constantly; never persist it.
    if p.name.lower().startswith("live."):
        return None

    mime = mimetypes.guess_type(str(p))[0] or "application/octet-stream"
    with p.open("rb") as f:
        files = {"file": (p.name, f, mime)}
        r = client.post(
            f"/api/sessions/{session_id}/local/upload-screenshot",
            params={"result_id": result_id, "label": label},
            files=files,
            timeout=120.0,
        )
    r.raise_for_status()
    data = r.json() or {}
    ref = data.get("ref")
    return str(ref) if ref else None


def _replace_screenshots_with_refs(
    client: httpx.Client,
    session_id: str,
    result: TestResult,
) -> None:
    result_id = str(result.id)

    # result.screenshot_urls
    new_urls: List[str] = []
    for raw in (result.screenshot_urls or []):
        if not raw:
            continue
        ref = _upload_screenshot(
            client,
            session_id,
            path=str(raw),
            result_id=result_id,
            label=Path(str(raw)).stem or "evidence",
        )
        if ref:
            new_urls.append(ref)
    result.screenshot_urls = new_urls

    # steps_results[*].screenshot
    for step in (result.steps_results or []):
        if not isinstance(step, dict):
            continue
        raw = step.get("screenshot")
        if not raw:
            continue
        label = str(step.get("step_id") or Path(str(raw)).stem or "turn")
        ref = _upload_screenshot(client, session_id, path=str(raw), result_id=result_id, label=label)
        if ref:
            step["screenshot"] = ref
        else:
            step.pop("screenshot", None)

    # scenario_results[*].turns[*].screenshot
    scenario_map = result.scenario_results if isinstance(result.scenario_results, dict) else {}
    for scenario in scenario_map.values():
        if not isinstance(scenario, dict):
            continue
        turns = scenario.get("turns")
        if not isinstance(turns, list):
            continue
        for turn in turns:
            if not isinstance(turn, dict):
                continue
            raw = turn.get("screenshot")
            if not raw:
                continue
            label = str(turn.get("step_id") or turn.get("turn") or Path(str(raw)).stem or "turn")
            ref = _upload_screenshot(client, session_id, path=str(raw), result_id=result_id, label=label)
            if ref:
                turn["screenshot"] = ref
            else:
                turn.pop("screenshot", None)

    # conversation_log (optional)
    if result.conversation_log:
        try:
            data = json.loads(result.conversation_log)
        except Exception:
            data = None
        if isinstance(data, list):
            changed = False
            for turn in data:
                if not isinstance(turn, dict) or not turn.get("screenshot"):
                    continue
                raw = turn.get("screenshot")
                ref = _upload_screenshot(
                    client,
                    session_id,
                    path=str(raw),
                    result_id=result_id,
                    label=str(turn.get("step_id") or turn.get("turn") or Path(str(raw)).stem or "turn"),
                )
                if ref:
                    turn["screenshot"] = ref
                    changed = True
                else:
                    turn.pop("screenshot", None)
                    changed = True
            if changed:
                result.conversation_log = json.dumps(data, ensure_ascii=False, default=str)


def run_session_local(
    *,
    session_id: str,
    backend_url: str,
    token: str,
    headless: bool = False,
    output_dir: str = "./output/local_runner",
    event_handler: Optional[Callable[[Dict[str, Any]], None]] = None,
    stop_requested: Optional[Callable[[], bool]] = None,
):
    """Run a cloud-created session locally and ingest results back into the cloud."""

    def _emit(event: Dict[str, Any]) -> None:
        if not event_handler:
            return
        try:
            event_handler(dict(event))
        except Exception:
            # Do not break execution because of UI/event bridge issues.
            pass

    backend = _normalize_backend_url(backend_url)
    headers = _auth_headers(token)

    # Fetch run configuration
    console.print(f"[dim]Fetching run config from {backend}...[/dim]")
    _emit({"type": "log", "level": "info", "message": f"Fetching run config from {backend}..."})
    with httpx.Client(base_url=backend, headers=headers, timeout=60.0) as client:
        r = client.get(f"/api/sessions/{session_id}/run-config")
        r.raise_for_status()
        payload = r.json() or {}

        session, bot, scenarios, personas, links = _build_models(payload)
        groups = _group_by_persona(scenarios, personas, links)
        if not groups:
            raise typer.Exit("No runnable scenario/persona links found for this session.")

        # AI proxy: use server-side keys, but pass the user's JWT as the bearer token.
        ai = AIClient(
            api_key=token,
            base_url=f"{backend}/api/ai/openai/v1",
            model=os.getenv("OPENAI_MODEL", "gpt-4.1-mini"),
            temperature=float(os.getenv("OPENAI_TEMPERATURE", "0.2")),
            max_tokens=int(os.getenv("OPENAI_MAX_TOKENS", "1000")),
            timeout=int(os.getenv("OPENAI_TIMEOUT", "60")),
        )

        rag = RAGEvaluator(ai)
        tone = ToneEvaluator(ai)
        turn_eval_enabled = env_bool("ENABLE_TURN_EVALUATOR", True)
        turn_eval = None
        if turn_eval_enabled:
            from src.core.ai_client import get_evaluator_client_from_env

            evaluator_ai = get_evaluator_client_from_env()
            turn_eval = TurnEvaluator(evaluator_ai)

        out_root = Path(output_dir) / str(session.id)
        out_root.mkdir(parents=True, exist_ok=True)

        engine = TestEngine(
            ai_client=ai,
            rag_evaluator=rag,
            tone_evaluator=tone,
            turn_evaluator=turn_eval,
            output_dir=str(out_root),
            event_handler=_emit,
            stop_requested=stop_requested,
            max_messages=(session.max_turns or session.max_messages),
            persona_system_prompt_override=get_effective_session_prompt(
                getattr(session, "config", None)
            ),
        )
        base_prompt_override = engine.persona_system_prompt_override

        results: List[TestResult] = []
        messages_sent_total = 0
        collected_errors: List[str] = []
        total_tests = sum(len(g.get("scenarios", [])) for g in groups.values())
        _emit({"type": "status", "status": "running", "total_tests": total_tests})
        _emit({"type": "log", "level": "info", "message": f"Starting session with {total_tests} test(s)."})
        local_stop_requested = False

        for group in groups.values():
            if stop_requested and stop_requested():
                local_stop_requested = True
                _emit({"type": "log", "level": "warning", "message": "Stop requested by operator. Finalizing partial results..."})
                break
            persona: Persona = group["persona"]
            scenario_list: List[Scenario] = group["scenarios"]
            engine.persona_system_prompt_override = (
                base_prompt_override or _build_group_prompt(persona, scenario_list)
            )
            console.print(f"\n[cyan]Running {len(scenario_list)} scenario(s) as {persona.name}[/cyan]")
            _emit({
                "type": "progress",
                "scenario": f"{len(scenario_list)} scenarios",
                "persona": persona.name,
            })
            _emit({"type": "log", "level": "info", "message": f"Running {len(scenario_list)} scenario(s) as {persona.name}"})

            result = engine.run_multi_scenario_test(
                bot=bot,
                scenarios=scenario_list,
                persona=persona,
                session=session,
                headless=headless,
            )
            messages_sent_total += int(getattr(engine, "messages_sent_count", 0) or 0)

            result_status = str(getattr(result, "status", "")).strip().lower()
            if result_status in {"error", "failed", "cancelled", "stopped"}:
                err = str(getattr(result, "error_message", "") or getattr(result, "failure_reason", "") or "").strip()
                if err:
                    collected_errors.append(err)
            if result_status == "stopped":
                local_stop_requested = True

            # Upload screenshots and replace paths with sb:// refs.
            _replace_screenshots_with_refs(client, session_id, result)
            results.append(result)
            if local_stop_requested:
                _emit({"type": "log", "level": "warning", "message": "Session interrupted manually. Uploading partial results..."})
                break

        if not results:
            stop_message = "Stopped before any scenario turn was recorded."
            _emit({"type": "log", "level": "warning", "message": stop_message})
            try:
                client.post(f"/api/sessions/{session_id}/stop", timeout=30.0)
                current = client.get(f"/api/sessions/{session_id}", timeout=30.0)
                current.raise_for_status()
                updated = current.json() or {}
            except Exception:
                updated = {
                    "status": "cancelled",
                    "passed": 0,
                    "failed": 0,
                    "error_message": stop_message,
                }
            _emit({
                "type": "status",
                "status": str(updated.get("status") or "cancelled"),
                "passed": int(updated.get("passed") or 0),
                "failed": int(updated.get("failed") or 0),
                "message": updated.get("error_message") or stop_message,
            })
            return updated

        ingest_payload = {
            "results": [r.model_dump(mode="json") for r in results],
            "messages_sent": messages_sent_total,
        }
        if local_stop_requested:
            ingest_payload["status"] = "manual_completed"
        if collected_errors:
            unique_errors = list(dict.fromkeys(collected_errors))
            ingest_payload["error_message"] = " | ".join(unique_errors)[:1800]
        console.print("\n[dim]Ingesting results into cloud...[/dim]")
        _emit({"type": "log", "level": "info", "message": "Ingesting results into cloud..."})
        r = client.post(f"/api/sessions/{session_id}/local/ingest", json=ingest_payload, timeout=120.0)
        r.raise_for_status()
        updated = r.json() or {}

        # Ensure caller receives an explicit failure reason when present on results.
        if not updated.get("error_message") and collected_errors:
            unique_errors = list(dict.fromkeys(collected_errors))
            updated["error_message"] = " | ".join(unique_errors)[:1800]

    console.print("[green]✓ Completed local run and ingested results.[/green]")
    console.print(f"[dim]Session status: {updated.get('status')} | passed={updated.get('passed')} failed={updated.get('failed')}[/dim]")
    if updated.get("error_message"):
        console.print(f"[yellow]Session detail: {updated.get('error_message')}[/yellow]")
    _emit({
        "type": "status",
        "status": str(updated.get("status") or "completed"),
        "passed": int(updated.get("passed") or 0),
        "failed": int(updated.get("failed") or 0),
        "message": updated.get("error_message") or "Local runner completed",
    })
    return updated


@app.command("run")
def run_session(
    session_id: str = typer.Argument(..., help="Test session ID (UUID)"),
    backend_url: str = typer.Option(..., "--backend-url", envvar="AI_TESTER_BACKEND_URL"),
    token: str = typer.Option(..., "--token", envvar="AI_TESTER_AUTH_TOKEN"),
    headless: bool = typer.Option(False, "--headless", help="Run browser headless (default: false)"),
    output_dir: str = typer.Option("./output/local_runner", "--output-dir"),
):
    """CLI entrypoint for local run + ingest."""
    run_session_local(
        session_id=session_id,
        backend_url=backend_url,
        token=token,
        headless=headless,
        output_dir=output_dir,
    )


if __name__ == "__main__":
    app()