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
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
#!/usr/bin/env python3
"""
AI Tester Platform CLI
Main entry point for the command-line interface.
"""

from contextlib import contextmanager
from pathlib import Path
from typing import List, Optional
from uuid import UUID

import typer
from dotenv import load_dotenv
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

# Load env vars
load_dotenv()

# Add src to path
import sys

sys.path.insert(0, str(Path(__file__).parent.parent))

from src.core import RAGEvaluator, TestEngine, ToneEvaluator, get_ai_client_from_env
from src.db import (
    BotRepository,
    PersonaRepository,
    ScenarioRepository,
    SessionRepository,
    get_db,
    init_db,
)
from src.models import Bot, Persona, Scenario, SessionStatus, TestSession
from src.utils.report_generator import ReportGenerator

app = typer.Typer(
    name="ai-tester",
    help="AI-powered testing platform for conversational chatbots",
    rich_markup_mode="rich",
)

console = Console()

# Helper to get DB session
@contextmanager
def get_repo(repo_class):
    """Context manager for repositories."""
    db = get_db()
    with db.get_session() as session:
        yield repo_class(session)


@app.callback()
def callback():
    """
    πŸ€– AI Tester Platform - Test your conversational AI with simulated users.
    
    Features:
    - Create and manage bot configurations
    - Define personas and test scenarios
    - Run automated conversational tests
    - Evaluate RAG faithfulness and tone-of-voice
    - Generate detailed reports
    """
    # Initialize database on first run
    init_db()


# ==================== BOT COMMANDS ====================

bot_app = typer.Typer(help="Manage bot configurations")
app.add_typer(bot_app, name="bot")


@bot_app.command("create")
def bot_create(
    name: str = typer.Argument(..., help="Bot name"),
    url: str = typer.Argument(..., help="Bot URL"),
    description: Optional[str] = typer.Option(None, "--description", "-d"),
):
    """Create a new bot configuration."""
    with get_repo(BotRepository) as repo:
        from src.models import RAGConfig, Selectors, ToneConfig
        
        bot = Bot(
            name=name,
            url=url,
            description=description,
            selectors=Selectors(),
            expected_tone=ToneConfig(),
            rag_config=RAGConfig(),
        )
        
        created = repo.create(bot)
        console.print(f"[green]βœ“ Created bot: {created.name} (ID: {created.id})[/green]")


@bot_app.command("list")
def bot_list():
    """List all configured bots."""
    with get_repo(BotRepository) as repo:
        bots = repo.list_all()
        
        if not bots:
            console.print("[yellow]No bots configured yet.[/yellow]")
            return
        
        table = Table(title="Configured Bots")
        table.add_column("ID", style="dim")
        table.add_column("Name", style="cyan")
        table.add_column("URL")
        table.add_column("Active", justify="center")
        
        for bot in bots:
            table.add_row(
                str(bot.id)[:8],
                bot.name,
                str(bot.url)[:50],
                "βœ“" if bot.is_active else "βœ—",
            )
        
        console.print(table)


@bot_app.command("show")
def bot_show(bot_id: str = typer.Argument(..., help="Bot ID")):
    """Show bot details."""
    with get_repo(BotRepository) as repo:
        bot = repo.get_by_id(UUID(bot_id))
        if not bot:
            console.print(f"[red]Bot not found: {bot_id}[/red]")
            raise typer.Exit(1)
        
        console.print(Panel(
            f"[bold]{bot.name}[/bold]\n\n"
            f"ID: {bot.id}\n"
            f"URL: {bot.url}\n"
            f"Description: {bot.description or 'N/A'}\n"
            f"Active: {bot.is_active}\n\n"
            f"Tone Config:\n"
            f"  - Formality: {bot.expected_tone.formality_level}/10\n"
            f"  - Emoji: {'Yes' if bot.expected_tone.use_emoji else 'No'}\n"
            f"  - Style: {bot.expected_tone.language_style}\n\n"
            f"RAG Config:\n"
            f"  - Faithfulness threshold: {bot.rag_config.faithfulness_threshold}\n"
            f"  - Strict mode: {bot.rag_config.strict_mode}",
            title="Bot Details"
        ))


# ==================== PERSONA COMMANDS ====================

persona_app = typer.Typer(help="Manage test personas")
app.add_typer(persona_app, name="persona")


@persona_app.command("create")
def persona_create(
    name: str = typer.Argument(..., help="Persona name"),
    mood: str = typer.Option("neutral", "--mood", "-m", help="Mood: friendly, angry, frustrated, etc"),
    goal: str = typer.Option(..., "--goal", "-g", help="Persona's goal"),
    background: Optional[str] = typer.Option(None, "--background", "-b"),
    template: bool = typer.Option(False, "--template", "-t", help="Save as reusable template"),
):
    """Create a new test persona."""
    with get_repo(PersonaRepository) as repo:
        persona = Persona(
            name=name,
            mood=mood,
            goal=goal,
            background=background,
            is_template=template,
        )
        
        created = repo.create(persona)
        console.print(f"[green]βœ“ Created persona: {created.name} (ID: {created.id})[/green]")


@persona_app.command("list")
def persona_list(
    templates_only: bool = typer.Option(False, "--templates", "-t"),
):
    """List personas."""
    with get_repo(PersonaRepository) as repo:
        personas = repo.list_all(templates_only=templates_only)
        
        if not personas:
            console.print("[yellow]No personas found.[/yellow]")
            return
        
        table = Table(title="Personas")
        table.add_column("ID", style="dim")
        table.add_column("Name", style="cyan")
        table.add_column("Mood")
        table.add_column("Template", justify="center")
        
        for p in personas:
            table.add_row(
                str(p.id)[:8],
                p.name,
                p.mood,
                "βœ“" if p.is_template else "",
            )
        
        console.print(table)


# ==================== SCENARIO COMMANDS ====================

scenario_app = typer.Typer(help="Manage test scenarios")
app.add_typer(scenario_app, name="scenario")


@scenario_app.command("create")
def scenario_create(
    name: str = typer.Argument(..., help="Scenario name"),
    steps_file: Optional[str] = typer.Option(None, "--steps-file", "-f", help="JSON file with steps"),
    template: bool = typer.Option(False, "--template", "-t"),
):
    """Create a new test scenario."""
    import json
    
    with get_repo(ScenarioRepository) as repo:
        if steps_file:
            with open(steps_file) as f:
                steps_data = json.load(f)
            from src.models import Step
            steps = [Step(**s) for s in steps_data]
        else:
            # Create default greeting scenario
            from src.models import ActionType, Step
            steps = [
                Step(
                    step_id="greeting",
                    action_type=ActionType.SEND_MESSAGE,
                    content="Hello!",
                    expected_intent="greeting",
                )
            ]
        
        scenario = Scenario(
            name=name,
            steps=steps,
            is_template=template,
        )
        
        created = repo.create(scenario)
        console.print(f"[green]βœ“ Created scenario: {created.name} (ID: {created.id})[/green]")


@scenario_app.command("list")
def scenario_list():
    """List scenarios."""
    with get_repo(ScenarioRepository) as repo:
        scenarios = repo.list_all()
        
        if not scenarios:
            console.print("[yellow]No scenarios found.[/yellow]")
            return
        
        table = Table(title="Scenarios")
        table.add_column("ID", style="dim")
        table.add_column("Name", style="cyan")
        table.add_column("Steps", justify="right")
        table.add_column("Category")
        
        for s in scenarios:
            table.add_row(
                str(s.id)[:8],
                s.name,
                str(len(s.steps)),
                s.category or "-",
            )
        
        console.print(table)


# ==================== SESSION COMMANDS ====================

session_app = typer.Typer(help="Manage and run test sessions")
app.add_typer(session_app, name="session")


@session_app.command("create")
def session_create(
    bot_id: str = typer.Argument(..., help="Bot ID to test"),
    version: str = typer.Argument(..., help="Bot version (e.g., v1.2.3)"),
    scenarios: List[str] = typer.Option(..., "--scenario", "-s", help="Scenario IDs to run"),
    personas: List[str] = typer.Option(..., "--persona", "-p", help="Persona IDs to use"),
    name: Optional[str] = typer.Option(None, "--name", "-n"),
):
    """Create a new test session."""
    with get_repo(SessionRepository) as repo:
        session = TestSession(
            bot_id=UUID(bot_id),
            bot_version=version,
            session_name=name,
            status=SessionStatus.PENDING,
        )
        
        created = repo.create_session(session)
        
        # Add scenario-persona links
        for scenario_id in scenarios:
            for persona_id in personas:
                from sqlalchemy import text
                repo.db.execute(
                    text("INSERT INTO session_scenario_links (session_id, scenario_id, persona_id) VALUES (:sid, :scid, :pid)"),
                    {"sid": str(created.id), "scid": str(scenario_id), "pid": str(persona_id)},
                )
        
        console.print(f"[green]βœ“ Created session: {created.id}[/green]")
        console.print(f"  Bot: {bot_id} (v{version})")
        console.print(f"  Scenarios: {len(scenarios)}")
        console.print(f"  Personas: {len(personas)}")
        console.print(f"  Total tests: {len(scenarios) * len(personas)}")


@session_app.command("run")
def session_run(
    session_id: str = typer.Argument(..., help="Session ID to run"),
    headless: bool = typer.Option(False, "--headless", help="Run browser headless"),
):
    """Run a test session."""
    # Setup
    try:
        ai_client = get_ai_client_from_env()
    except ValueError as e:
        console.print(f"[red]Error: {e}[/red]")
        raise typer.Exit(1)
    
    rag_eval = RAGEvaluator(ai_client)
    tone_eval = ToneEvaluator(ai_client)
    
    with get_repo(SessionRepository) as session_repo:
        with get_repo(BotRepository) as bot_repo:
            with get_repo(ScenarioRepository) as scenario_repo:
                with get_repo(PersonaRepository) as persona_repo:
                    session = session_repo.get_session(UUID(session_id))
                    if not session:
                        console.print(f"[red]Session not found: {session_id}[/red]")
                        raise typer.Exit(1)
                    
                    bot = bot_repo.get_by_id(session.bot_id)
                    if not bot:
                        console.print("[red]Bot not found[/red]")
                        raise typer.Exit(1)
                    
                    # Get scenario-persona combinations
                    links = session_repo.list_session_links(UUID(session_id))
                    pairs = []
                    if links:
                        for link in links:
                            scenario = scenario_repo.get_by_id(UUID(link["scenario_id"]))
                            persona = persona_repo.get_by_id(UUID(link["persona_id"]))
                            if scenario and persona:
                                pairs.append((scenario, persona))
                    if not pairs:
                        scenarios = scenario_repo.list_all(bot_id=bot.id)
                        personas = persona_repo.list_all()
                        for scenario in scenarios:
                            for persona in personas:
                                pairs.append((scenario, persona))
                    
                    engine = TestEngine(
                        ai_client=ai_client,
                        rag_evaluator=rag_eval,
                        tone_evaluator=tone_eval,
                        output_dir=f"./output/{session_id}",
                    )
                    
                    # Run tests
                    total = len(pairs)
                    completed = 0
                    passed = 0
                    failed = 0
                    
                    for scenario, persona in pairs:
                        console.print(f"\n[cyan]Running: {scenario.name} as {persona.name}[/cyan]")
                        
                        result = engine.run_test(
                            bot=bot,
                            scenario=scenario,
                            persona=persona,
                            session=session,
                            headless=headless,
                        )
                        
                        session_repo.add_result(result)
                        completed += 1
                        if result.status == "passed":
                            passed += 1
                        else:
                            failed += 1
                        
                        status_color = "green" if result.status == "passed" else "red"
                        console.print(f"[{status_color}]Result: {result.status}[/{status_color}]")
                    
                    # Update session status
                    session_repo.update_session(
                        UUID(session_id),
                        {
                            "status": "completed",
                            "total_tests": total,
                            "passed": passed,
                            "failed": failed,
                            "completed_at": datetime.now(),
                        }
                    )
                    
                    console.print(f"\n[green]βœ“ Session completed: {completed}/{total} tests[/green]")


@session_app.command("list")
def session_list(
    bot_id: Optional[str] = typer.Option(None, "--bot", "-b"),
):
    """List test sessions."""
    with get_repo(SessionRepository) as repo:
        bot_uuid = UUID(bot_id) if bot_id else None
        sessions = repo.list_sessions(bot_uuid)
        
        if not sessions:
            console.print("[yellow]No sessions found.[/yellow]")
            return
        
        table = Table(title="Test Sessions")
        table.add_column("ID", style="dim")
        table.add_column("Name", style="cyan")
        table.add_column("Version")
        table.add_column("Status")
        table.add_column("Results", justify="right")
        table.add_column("Date")
        
        for s in sessions:
            status_color = {
                "pending": "yellow",
                "running": "blue",
                "completed": "green",
                "failed": "red",
            }.get(s.status.value, "white")
            
            table.add_row(
                str(s.id)[:8],
                s.session_name or "-",
                s.bot_version,
                f"[{status_color}]{s.status.value}[/{status_color}]",
                f"{s.passed}/{s.total_tests}",
                s.created_at.strftime("%Y-%m-%d %H:%M") if s.created_at else "-",
            )
        
        console.print(table)


@session_app.command("report")
def session_report(
    session_id: str = typer.Argument(..., help="Session ID"),
    format: str = typer.Option("markdown", "--format", "-f", help="Output format: json, markdown, html"),
    output: Optional[str] = typer.Option(None, "--output", "-o", help="Output file"),
):
    """Generate session report."""
    with get_repo(SessionRepository) as repo:
        session = repo.get_session(UUID(session_id))
        if not session:
            console.print("[red]Session not found[/red]")
            raise typer.Exit(1)
        
        results = repo.get_session_results(UUID(session_id))
        
        generator = ReportGenerator()
        
        if format == "json":
            report = generator.to_json(session, results)
        elif format == "markdown":
            report = generator.to_markdown(session, results)
        else:
            report = generator.to_html(session, results)
        
        if output:
            with open(output, "w") as f:
                f.write(report)
            console.print(f"[green]Report saved to: {output}[/green]")
        else:
            console.print(report)


if __name__ == "__main__":
    from datetime import datetime
    app()