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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
"""Studio CLI commands for generation (audio, report, quiz, etc.)."""

from typing import Optional

import typer
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn

from notebooklm_tools.core.alias import get_alias_manager
from notebooklm_tools.core.exceptions import NLMError
from notebooklm_tools.cli.formatters import detect_output_format, get_formatter
from notebooklm_tools.cli.utils import get_client
from notebooklm_tools.services import studio as studio_service, ServiceError, ValidationError

console = Console()

# Main studio app for status/delete
app = typer.Typer(
    help="Manage studio artifacts",
    rich_markup_mode="rich",
    no_args_is_help=True,
)

# Individual generation apps
audio_app = typer.Typer(
    help="Create audio overviews",
    rich_markup_mode="rich",
    no_args_is_help=True,
)
report_app = typer.Typer(
    help="Create reports",
    rich_markup_mode="rich",
    no_args_is_help=True,
)
quiz_app = typer.Typer(
    help="Create quizzes",
    rich_markup_mode="rich",
    no_args_is_help=True,
)
flashcards_app = typer.Typer(
    help="Create flashcards",
    rich_markup_mode="rich",
    no_args_is_help=True,
)
mindmap_app = typer.Typer(
    help="Create and manage mind maps",
    rich_markup_mode="rich",
    no_args_is_help=True,
)
slides_app = typer.Typer(
    help="Create slide decks",
    rich_markup_mode="rich",
    no_args_is_help=True,
)
infographic_app = typer.Typer(
    help="Create infographics",
    rich_markup_mode="rich",
    no_args_is_help=True,
)
video_app = typer.Typer(
    help="Create video overviews",
    rich_markup_mode="rich",
    no_args_is_help=True,
)
data_table_app = typer.Typer(
    help="Create data tables",
    rich_markup_mode="rich",
    no_args_is_help=True,
)


def parse_source_ids(source_ids: str | None) -> list[str] | None:
    """Parse comma-separated source IDs."""
    if source_ids:
        return [get_alias_manager().resolve(s.strip()) for s in source_ids.split(",")]
    return None


def _run_create(
    notebook_id: str,
    artifact_type: str,
    label: str,
    profile: Optional[str],
    **kwargs,
) -> None:
    """Shared CLI creation logic: spinner + service call + formatted output.

    CLI-specific concerns (confirmation, arg parsing) happen in each command.
    This helper handles the common pattern of spinner β†’ create β†’ print result.
    """
    try:
        notebook_id = get_alias_manager().resolve(notebook_id)
        with Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
            console=console,
        ) as progress:
            progress.add_task(f"Creating {label}...", total=None)
            with get_client(profile) as client:
                result = studio_service.create_artifact(
                    client, notebook_id, artifact_type, **kwargs,
                )

        # Mind map has a different result shape
        if artifact_type == "mind_map":
            console.print(f"[green]βœ“[/green] Mind map created")
            console.print(f"  ID: {result.get('artifact_id', 'unknown')}")
            console.print(f"  Title: {result.get('title', 'Mind Map')}")
        else:
            console.print(f"[green]βœ“[/green] {label.title()} generation started")
            console.print(f"  Artifact ID: {result.get('artifact_id', 'unknown')}")
            console.print(f"\n[dim]Run 'nlm studio status {notebook_id}' to check progress.[/dim]")
    except (ValidationError, ServiceError) as e:
        msg = e.user_message if isinstance(e, ServiceError) else str(e)
        console.print(f"[red]Error:[/red] {msg}")
        if isinstance(e, ServiceError) and "rejected" in str(e):
            console.print("[dim]Try again later or create from NotebookLM UI for diagnosis.[/dim]")
        raise typer.Exit(1)
    except NLMError as e:
        console.print(f"[red]Error:[/red] {e.message}")
        if e.hint:
            console.print(f"\n[dim]Hint: {e.hint}[/dim]")
        raise typer.Exit(1)


# ========== Studio Status/Delete ==========

@app.command("status")
def studio_status(
    notebook_id: str = typer.Argument(..., help="Notebook ID"),
    full: bool = typer.Option(False, "--full", "-a", help="Show all details"),
    json_output: bool = typer.Option(False, "--json", "-j", help="Output as JSON"),
    profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Profile to use"),
) -> None:
    """List all studio artifacts and their status."""
    try:
        notebook_id = get_alias_manager().resolve(notebook_id)
        with get_client(profile) as client:
            artifacts = client.poll_studio_status(notebook_id)

        fmt = detect_output_format(json_output)
        formatter = get_formatter(fmt, console)
        formatter.format_artifacts(artifacts, full=full)
    except NLMError as e:
        console.print(f"[red]Error:[/red] {e.message}")
        if e.hint:
            console.print(f"\n[dim]Hint: {e.hint}[/dim]")
        raise typer.Exit(1)


@app.command("delete")
def studio_delete(
    notebook_id: str = typer.Argument(..., help="Notebook ID"),
    artifact_id: str = typer.Argument(..., help="Artifact ID to delete"),
    confirm: bool = typer.Option(False, "--confirm", "-y", help="Skip confirmation"),
    profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Profile to use"),
) -> None:
    """Delete a studio artifact permanently."""
    notebook_id = get_alias_manager().resolve(notebook_id)
    artifact_id = get_alias_manager().resolve(artifact_id)

    if not confirm:
        typer.confirm(f"Are you sure you want to delete artifact {artifact_id}?", abort=True)

    try:
        with get_client(profile) as client:
            studio_service.delete_artifact(client, artifact_id, notebook_id)
        console.print(f"[green]βœ“[/green] Deleted artifact: {artifact_id}")
    except ServiceError as e:
        console.print(f"[red]Error:[/red] {e.user_message}")
        raise typer.Exit(1)
    except NLMError as e:
        console.print(f"[red]Error:[/red] {e.message}")
        if e.hint:
            console.print(f"\n[dim]Hint: {e.hint}[/dim]")
        raise typer.Exit(1)


@app.command("rename")
def studio_rename(
    artifact_id: str = typer.Argument(..., help="Artifact ID to rename"),
    new_title: str = typer.Argument(..., help="New title for the artifact"),
    profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Profile to use"),
) -> None:
    """Rename a studio artifact."""
    artifact_id = get_alias_manager().resolve(artifact_id)

    try:
        with get_client(profile) as client:
            result = studio_service.rename_artifact(client, artifact_id, new_title)
        console.print(f"[green]βœ“[/green] Renamed artifact to: {result['new_title']}")
    except (ValidationError, ServiceError) as e:
        msg = e.user_message if isinstance(e, ServiceError) else str(e)
        console.print(f"[red]Error:[/red] {msg}")
        raise typer.Exit(1)
    except NLMError as e:
        console.print(f"[red]Error:[/red] {e.message}")
        if e.hint:
            console.print(f"\n[dim]Hint: {e.hint}[/dim]")
        raise typer.Exit(1)


# ========== Audio ==========

@audio_app.command("create")
def create_audio(
    notebook_id: str = typer.Argument(..., help="Notebook ID"),
    format: str = typer.Option(
        "deep_dive", "--format", "-f",
        help="Overview format (deep_dive, brief, critique, debate)",
    ),
    length: str = typer.Option(
        "default", "--length", "-l",
        help="Length (short, default, long)",
    ),
    language: str = typer.Option(
        "en", "--language",
        help="BCP-47 language code (en, es, fr, de, ja)",
    ),
    focus: Optional[str] = typer.Option(
        None, "--focus",
        help="Optional focus topic",
    ),
    source_ids: Optional[str] = typer.Option(
        None, "--source-ids", "-s",
        help="Comma-separated source IDs",
    ),
    confirm: bool = typer.Option(False, "--confirm", "-y", help="Skip confirmation"),
    profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Profile to use"),
) -> None:
    """Create an audio overview (podcast) from notebook sources."""
    if not confirm:
        typer.confirm(f"Create {format} audio overview?", abort=True)

    _run_create(
        notebook_id, "audio", "audio",
        profile=profile,
        source_ids=parse_source_ids(source_ids),
        audio_format=format, audio_length=length,
        language=language, focus_prompt=focus or "",
    )


# ========== Report ==========

@report_app.command("create")
def create_report(
    notebook_id: str = typer.Argument(..., help="Notebook ID"),
    format: str = typer.Option(
        "Briefing Doc", "--format", "-f",
        help="Format: 'Briefing Doc', 'Study Guide', 'Blog Post', 'Create Your Own'",
    ),
    prompt: str = typer.Option("", "--prompt", help="Custom prompt (required for 'Create Your Own')"),
    language: str = typer.Option("en", "--language", help="BCP-47 language code"),
    source_ids: Optional[str] = typer.Option(None, "--source-ids", "-s", help="Comma-separated source IDs"),
    confirm: bool = typer.Option(False, "--confirm", "-y", help="Skip confirmation"),
    profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Profile to use"),
) -> None:
    """Create a report from notebook sources."""
    if format == "Create Your Own" and not prompt:
        console.print("[red]Error:[/red] --prompt is required when format is 'Create Your Own'")
        raise typer.Exit(1)

    if not confirm:
        typer.confirm(f"Create '{format}' report?", abort=True)

    _run_create(
        notebook_id, "report", "report",
        profile=profile,
        source_ids=parse_source_ids(source_ids),
        report_format=format, custom_prompt=prompt,
        language=language,
    )


# ========== Quiz ==========

@quiz_app.command("create")
def create_quiz(
    notebook_id: str = typer.Argument(..., help="Notebook ID"),
    count: int = typer.Option(2, "--count", "-c", help="Number of questions"),
    difficulty: int = typer.Option(2, "--difficulty", "-d", help="Difficulty 1-5 (1=easy, 5=hard)"),
    focus: Optional[str] = typer.Option(None, "--focus", "-f", help="Focus prompt to guide generation"),
    source_ids: Optional[str] = typer.Option(None, "--source-ids", "-s", help="Comma-separated source IDs"),
    confirm: bool = typer.Option(False, "--confirm", "-y", help="Skip confirmation"),
    profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Profile to use"),
) -> None:
    """Create a quiz from notebook sources."""
    if not confirm:
        typer.confirm(f"Create quiz with {count} questions?", abort=True)

    # Quiz CLI sends raw int codes directly β€” bypass service string resolution
    try:
        notebook_id_resolved = get_alias_manager().resolve(notebook_id)
        with Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
            console=console,
        ) as progress:
            progress.add_task("Creating quiz...", total=None)
            with get_client(profile) as client:
                result = client.create_quiz(
                    notebook_id_resolved,
                    question_count=count,
                    difficulty=difficulty,
                    source_ids=parse_source_ids(source_ids),
                    focus_prompt=focus or "",
                )

        if not result or not result.get("artifact_id"):
            console.print("[red]Error:[/red] NotebookLM rejected quiz creation (no artifact returned).")
            console.print("[dim]Try again later or create from NotebookLM UI for diagnosis.[/dim]")
            raise typer.Exit(1)

        console.print("[green]βœ“[/green] Quiz generation started")
        console.print(f"  Artifact ID: {result.get('artifact_id', 'unknown')}")
        console.print(f"\n[dim]Run 'nlm studio status {notebook_id_resolved}' to check progress.[/dim]")
    except NLMError as e:
        console.print(f"[red]Error:[/red] {e.message}")
        if e.hint:
            console.print(f"\n[dim]Hint: {e.hint}[/dim]")
        raise typer.Exit(1)


# ========== Flashcards ==========

@flashcards_app.command("create")
def create_flashcards(
    notebook_id: str = typer.Argument(..., help="Notebook ID"),
    difficulty: str = typer.Option("medium", "--difficulty", "-d", help="Difficulty: easy, medium, hard"),
    focus: Optional[str] = typer.Option(None, "--focus", "-f", help="Focus prompt to guide generation"),
    source_ids: Optional[str] = typer.Option(None, "--source-ids", "-s", help="Comma-separated source IDs"),
    confirm: bool = typer.Option(False, "--confirm", "-y", help="Skip confirmation"),
    profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Profile to use"),
) -> None:
    """Create flashcards from notebook sources."""
    if not confirm:
        typer.confirm("Create flashcards?", abort=True)

    _run_create(
        notebook_id, "flashcards", "flashcards",
        profile=profile,
        source_ids=parse_source_ids(source_ids),
        difficulty=difficulty,
        focus_prompt=focus or "",
    )


# ========== Mind Map ==========

@mindmap_app.command("create")
def create_mindmap(
    notebook_id: str = typer.Argument(..., help="Notebook ID"),
    title: str = typer.Option("Mind Map", "--title", "-t", help="Mind map title"),
    source_ids: Optional[str] = typer.Option(None, "--source-ids", "-s", help="Comma-separated source IDs"),
    confirm: bool = typer.Option(False, "--confirm", "-y", help="Skip confirmation"),
    profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Profile to use"),
) -> None:
    """Create a mind map from notebook sources."""
    if not confirm:
        typer.confirm("Create mind map?", abort=True)

    _run_create(
        notebook_id, "mind_map", "mind map",
        profile=profile,
        source_ids=parse_source_ids(source_ids),
        title=title,
    )


# Note: mindmap list removed - use 'studio status' which now includes mindmaps


# ========== Slides ==========

@slides_app.command("create")
def create_slides(
    notebook_id: str = typer.Argument(..., help="Notebook ID"),
    format: str = typer.Option("detailed_deck", "--format", "-f", help="Format: detailed_deck, presenter_slides"),
    length: str = typer.Option("default", "--length", "-l", help="Length: short, default"),
    language: str = typer.Option("en", "--language", help="BCP-47 language code"),
    focus: str = typer.Option("", "--focus", help="Optional focus topic"),
    source_ids: Optional[str] = typer.Option(None, "--source-ids", "-s", help="Comma-separated source IDs"),
    confirm: bool = typer.Option(False, "--confirm", "-y", help="Skip confirmation"),
    profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Profile to use"),
) -> None:
    """Create a slide deck from notebook sources."""
    if not confirm:
        typer.confirm("Create slide deck?", abort=True)

    _run_create(
        notebook_id, "slide_deck", "slide deck",
        profile=profile,
        source_ids=parse_source_ids(source_ids),
        slide_format=format, slide_length=length,
        language=language, focus_prompt=focus,
    )


# ========== Infographic ==========

@infographic_app.command("create")
def create_infographic(
    notebook_id: str = typer.Argument(..., help="Notebook ID"),
    orientation: str = typer.Option("landscape", "--orientation", "-o", help="Orientation: landscape, portrait, square"),
    detail: str = typer.Option("standard", "--detail", "-d", help="Detail level: concise, standard, detailed"),
    language: str = typer.Option("en", "--language", help="BCP-47 language code"),
    focus: str = typer.Option("", "--focus", help="Optional focus topic"),
    source_ids: Optional[str] = typer.Option(None, "--source-ids", "-s", help="Comma-separated source IDs"),
    confirm: bool = typer.Option(False, "--confirm", "-y", help="Skip confirmation"),
    profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Profile to use"),
) -> None:
    """Create an infographic from notebook sources."""
    if not confirm:
        typer.confirm("Create infographic?", abort=True)

    _run_create(
        notebook_id, "infographic", "infographic",
        profile=profile,
        source_ids=parse_source_ids(source_ids),
        orientation=orientation, detail_level=detail,
        language=language, focus_prompt=focus,
    )


# ========== Video ==========

@video_app.command("create")
def create_video(
    notebook_id: str = typer.Argument(..., help="Notebook ID"),
    format: str = typer.Option("explainer", "--format", "-f", help="Format: explainer, brief"),
    style: str = typer.Option(
        "auto_select", "--style", "-s",
        help="Visual style: auto_select, classic, whiteboard, kawaii, anime, watercolor, retro_print, heritage, paper_craft",
    ),
    language: str = typer.Option("en", "--language", help="BCP-47 language code"),
    focus: str = typer.Option("", "--focus", help="Optional focus topic"),
    source_ids: Optional[str] = typer.Option(None, "--source-ids", help="Comma-separated source IDs"),
    confirm: bool = typer.Option(False, "--confirm", "-y", help="Skip confirmation"),
    profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Profile to use"),
) -> None:
    """Create a video overview from notebook sources."""
    if not confirm:
        typer.confirm("Create video overview?", abort=True)

    _run_create(
        notebook_id, "video", "video",
        profile=profile,
        source_ids=parse_source_ids(source_ids),
        video_format=format, visual_style=style,
        language=language, focus_prompt=focus,
    )


# ========== Data Table ==========

@data_table_app.command("create")
def create_data_table(
    notebook_id: str = typer.Argument(..., help="Notebook ID"),
    description: str = typer.Argument(..., help="Description of the data table to create"),
    language: str = typer.Option("en", "--language", help="BCP-47 language code"),
    source_ids: Optional[str] = typer.Option(None, "--source-ids", "-s", help="Comma-separated source IDs"),
    confirm: bool = typer.Option(False, "--confirm", "-y", help="Skip confirmation"),
    profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Profile to use"),
) -> None:
    """Create a data table from notebook sources."""
    if not confirm:
        typer.confirm("Create data table?", abort=True)

    _run_create(
        notebook_id, "data_table", "data table",
        profile=profile,
        source_ids=parse_source_ids(source_ids),
        description=description, language=language,
    )