Coverage for fastblocks / mcp / config_cli.py: 0%

322 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-02 20:00 -0800

1"""Interactive CLI for FastBlocks adapter configuration management.""" 

2 

3import asyncio 

4import json 

5import os 

6import sys 

7import typing as t 

8from pathlib import Path 

9from typing import Any 

10 

11import click 

12from oneiric.core.resolution import Resolver 

13 

14# Use standard rich console instead of ACB console 

15from rich.console import Console 

16 

17# Oneiric resolver for dependency injection 

18depends = Resolver() 

19from mcp_common.ui import ServerPanels 

20from rich.panel import Panel 

21from rich.prompt import Confirm, Prompt 

22 

23from .configuration import ( 

24 ConfigurationManager, 

25 ConfigurationProfile, 

26 ConfigurationSchema, 

27 ConfigurationStatus, 

28 ConfigurationValidationResult, 

29 EnvironmentVariable, 

30) 

31from .health import HealthCheckSystem 

32from .registry import AdapterRegistry 

33 

34console = depends.get_sync(Console) 

35 

36 

37class InteractiveConfigurationCLI: 

38 """Interactive CLI for adapter configuration.""" 

39 

40 def __init__(self) -> None: 

41 """Initialize the interactive CLI.""" 

42 self.registry = AdapterRegistry() 

43 self.health = HealthCheckSystem(self.registry) 

44 self.config_manager = ConfigurationManager(self.registry) 

45 

46 async def initialize(self) -> None: 

47 """Initialize all systems.""" 

48 await self.registry.initialize() 

49 await self.config_manager.initialize() 

50 

51 async def run_configuration_wizard(self) -> ConfigurationSchema: 

52 """Run the interactive configuration wizard.""" 

53 console.print( 

54 Panel.fit( 

55 "[bold blue]FastBlocks Adapter Configuration Wizard[/bold blue]\n" 

56 "This wizard will help you configure FastBlocks adapters for your project.", 

57 title="Welcome", 

58 ) 

59 ) 

60 

61 # Step 1: Select profile 

62 profile = self._select_profile() 

63 

64 # Step 2: Select adapters 

65 selected_adapters = await self._select_adapters() 

66 

67 # Step 3: Configure selected adapters 

68 config = await self.config_manager.create_configuration( 

69 profile=profile, adapters=selected_adapters 

70 ) 

71 

72 # Step 4: Configure each adapter 

73 for adapter_name in selected_adapters: 

74 await self._configure_adapter_interactive(config, adapter_name) 

75 

76 # Step 5: Configure global settings 

77 await self._configure_global_settings(config) 

78 

79 # Step 6: Validate configuration 

80 console.print("\n[yellow]Validating configuration...[/yellow]") 

81 validation_result = await self.config_manager.validate_configuration(config) 

82 self._display_validation_result(validation_result) 

83 

84 if validation_result.status == ConfigurationStatus.ERROR: 

85 if not Confirm.ask("Configuration has errors. Continue anyway?"): 

86 console.print("[red]Configuration cancelled.[/red]") 

87 sys.exit(1) 

88 

89 # Step 7: Save configuration 

90 config_name = Prompt.ask( 

91 "Configuration name", default=f"{profile.value}_config" 

92 ) 

93 

94 config_file = await self.config_manager.save_configuration(config, config_name) 

95 console.print(f"\n[green]✓[/green] Configuration saved to: {config_file}") 

96 

97 # Step 8: Generate environment file 

98 if Confirm.ask("Generate .env file?", default=True): 

99 env_file = await self.config_manager.generate_environment_file(config) 

100 console.print(f"[green]✓[/green] Environment file created: {env_file}") 

101 

102 # Step 9: Create backup 

103 if Confirm.ask("Create backup?", default=True): 

104 backup_description = Prompt.ask( 

105 "Backup description", default="Initial configuration" 

106 ) 

107 backup = await self.config_manager.backup_configuration( 

108 config, config_name, backup_description 

109 ) 

110 console.print(f"[green]✓[/green] Backup created: {backup.id}") 

111 

112 return config 

113 

114 def _select_profile(self) -> ConfigurationProfile: 

115 """Interactive profile selection.""" 

116 console.print("\n[bold]Select deployment profile:[/bold]") 

117 

118 profiles = { 

119 "1": ( 

120 ConfigurationProfile.DEVELOPMENT, 

121 "Development - Debug enabled, relaxed security", 

122 ), 

123 "2": ( 

124 ConfigurationProfile.STAGING, 

125 "Staging - Production-like with debug options", 

126 ), 

127 "3": ( 

128 ConfigurationProfile.PRODUCTION, 

129 "Production - Optimized for performance and security", 

130 ), 

131 } 

132 

133 for key, (profile, description) in profiles.items(): 

134 console.print( 

135 f" {key}. [cyan]{profile.value.title()}[/cyan] - {description}" 

136 ) 

137 

138 choice = Prompt.ask( 

139 "Choose profile", choices=list(profiles.keys()), default="1" 

140 ) 

141 

142 selected_profile, _ = profiles[choice] 

143 console.print( 

144 f"[green]✓[/green] Selected profile: [cyan]{selected_profile.value.title()}[/cyan]" 

145 ) 

146 return selected_profile 

147 

148 def _group_adapters_by_category( 

149 self, available_adapters: dict[str, Any] 

150 ) -> dict[str, list[tuple[str, Any]]]: 

151 """Group adapters by category. 

152 

153 Args: 

154 available_adapters: Dict of adapter name -> adapter info 

155 

156 Returns: 

157 Dict of category -> list of (adapter_name, adapter_info) 

158 """ 

159 categories: dict[str, list[tuple[str, Any]]] = {} 

160 

161 for adapter_name, adapter_info in available_adapters.items(): 

162 category = adapter_info.category 

163 if category not in categories: 

164 categories[category] = [] 

165 categories[category].append((adapter_name, adapter_info)) 

166 

167 return categories 

168 

169 def _display_adapter_choices( 

170 self, categories: dict[str, list[tuple[str, Any]]] 

171 ) -> dict[str, str]: 

172 """Display adapters by category and build choice mapping. 

173 

174 Args: 

175 categories: Dict of category -> list of (adapter_name, adapter_info) 

176 

177 Returns: 

178 Dict mapping choice number to adapter name 

179 """ 

180 adapter_choices = {} 

181 choice_num = 1 

182 

183 for category, adapters in sorted(categories.items()): 

184 console.print(f"\n[bold yellow]{category.title()}:[/bold yellow]") 

185 for adapter_name, adapter_info in sorted(adapters): 

186 status_color = ( 

187 "green" if adapter_info.module_status == "stable" else "yellow" 

188 ) 

189 console.print( 

190 f" {choice_num:2d}. [cyan]{adapter_name:<20}[/cyan] " 

191 f"[{status_color}]{adapter_info.module_status:<12}[/{status_color}] " 

192 f"{adapter_info.description or 'No description'}" 

193 ) 

194 adapter_choices[str(choice_num)] = adapter_name 

195 choice_num += 1 

196 

197 return adapter_choices 

198 

199 def _get_recommended_adapters( 

200 self, available_adapters: dict[str, Any] 

201 ) -> list[str]: 

202 """Get recommended default adapters. 

203 

204 Args: 

205 available_adapters: Dict of available adapters 

206 

207 Returns: 

208 List of recommended adapter names 

209 """ 

210 recommended = ["app", "templates", "routes"] 

211 selected = [name for name in recommended if name in available_adapters] 

212 console.print( 

213 f"[green]✓[/green] Using recommended adapters: {', '.join(selected)}" 

214 ) 

215 return selected 

216 

217 def _parse_adapter_selection( 

218 self, selection: str, adapter_choices: dict[str, str] 

219 ) -> list[str]: 

220 """Parse user's adapter selection. 

221 

222 Args: 

223 selection: Comma-separated choice numbers 

224 adapter_choices: Dict mapping choice number to adapter name 

225 

226 Returns: 

227 List of selected adapter names 

228 """ 

229 selected_adapters = [] 

230 

231 for choice in selection.split(","): 

232 choice = choice.strip() 

233 if choice in adapter_choices: 

234 selected_adapters.append(adapter_choices[choice]) 

235 else: 

236 console.print(f"[red]Warning:[/red] Invalid choice '{choice}' ignored") 

237 

238 # Print result 

239 if selected_adapters: 

240 console.print( 

241 f"[green]✓[/green] Selected adapters: {', '.join(selected_adapters)}" 

242 ) 

243 else: 

244 console.print("[red]No adapters selected![/red]") 

245 

246 return selected_adapters 

247 

248 async def _select_adapters(self) -> list[str]: 

249 """Interactive adapter selection.""" 

250 console.print("\n[bold]Available Adapters:[/bold]") 

251 

252 available_adapters = await self.config_manager.get_available_adapters() 

253 

254 # Group and display adapters 

255 categories = self._group_adapters_by_category(available_adapters) 

256 adapter_choices = self._display_adapter_choices(categories) 

257 

258 # Get user selection 

259 console.print( 

260 "\n[bold]Select adapters (comma-separated numbers, e.g., 1,3,5):[/bold]" 

261 ) 

262 console.print("[dim]Leave empty for recommended defaults[/dim]") 

263 selection = Prompt.ask("Adapter numbers", default="") 

264 

265 # Return recommended or parsed selection 

266 if not selection.strip(): 

267 return self._get_recommended_adapters(available_adapters) 

268 

269 return self._parse_adapter_selection(selection, adapter_choices) 

270 

271 def _configure_adapter_env_vars(self, adapter_config: t.Any) -> None: 

272 """Configure adapter environment variables.""" 

273 if adapter_config.environment_variables: 

274 console.print("\n[yellow]Environment Variables:[/yellow]") 

275 for env_var in adapter_config.environment_variables: 

276 self._configure_environment_variable(env_var) 

277 

278 def _configure_required_settings( 

279 self, adapter_config: t.Any, schema: dict[str, t.Any] 

280 ) -> None: 

281 """Configure required adapter settings.""" 

282 for setting in schema.get("required_settings", []): 

283 value = Prompt.ask( 

284 f"[red]*[/red] {setting['name']} ({setting['type']})", 

285 default=str(setting.get("default", "")), 

286 ) 

287 adapter_config.settings[setting["name"]] = self._parse_setting_value( 

288 value, setting["type"] 

289 ) 

290 

291 def _configure_optional_settings( 

292 self, adapter_config: t.Any, schema: dict[str, t.Any] 

293 ) -> None: 

294 """Configure optional adapter settings.""" 

295 if schema.get("optional_settings") and Confirm.ask( 

296 "Configure optional settings?" 

297 ): 

298 for setting in schema.get("optional_settings", []): 

299 if Confirm.ask(f"Configure {setting['name']}?"): 

300 value = Prompt.ask( 

301 f"{setting['name']} ({setting['type']})", 

302 default=str(setting.get("default", "")), 

303 ) 

304 adapter_config.settings[setting["name"]] = ( 

305 self._parse_setting_value(value, setting["type"]) 

306 ) 

307 

308 async def _configure_adapter_interactive( 

309 self, config: ConfigurationSchema, adapter_name: str 

310 ) -> None: 

311 """Configure a specific adapter interactively.""" 

312 console.print(f"\n[bold]Configuring {adapter_name} adapter:[/bold]") 

313 

314 adapter_config = config.adapters[adapter_name] 

315 schema = await self.config_manager.get_adapter_configuration_schema( 

316 adapter_name 

317 ) 

318 

319 # Show adapter information 

320 console.print(f"[dim]Category: {schema.get('category', 'Unknown')}[/dim]") 

321 if schema.get("description"): 

322 console.print(f"[dim]Description: {schema['description']}[/dim]") 

323 

324 # Configure environment variables 

325 self._configure_adapter_env_vars(adapter_config) 

326 

327 # Configure settings 

328 if schema.get("required_settings") or schema.get("optional_settings"): 

329 console.print("\n[yellow]Adapter Settings:[/yellow]") 

330 self._configure_required_settings(adapter_config, schema) 

331 self._configure_optional_settings(adapter_config, schema) 

332 

333 # Configure dependencies 

334 if schema.get("dependencies"): 

335 console.print( 

336 f"\n[yellow]Dependencies: {', '.join(schema['dependencies'])}[/yellow]" 

337 ) 

338 adapter_config.dependencies.update(schema["dependencies"]) 

339 

340 def _configure_environment_variable(self, env_var: EnvironmentVariable) -> None: 

341 """Configure a single environment variable.""" 

342 current_value = os.environ.get( 

343 env_var.name, env_var.value or env_var.default or "" 

344 ) 

345 

346 if env_var.required: 

347 prompt_text = f"[red]*[/red] {env_var.name}" 

348 else: 

349 prompt_text = env_var.name 

350 

351 if env_var.description: 

352 console.print(f"[dim] {env_var.description}[/dim]") 

353 

354 if env_var.secret: 

355 value = Prompt.ask(prompt_text, password=True, default=current_value) 

356 else: 

357 value = Prompt.ask(prompt_text, default=current_value) 

358 

359 env_var.value = value 

360 

361 def _parse_setting_value(self, value: str, type_name: str) -> Any: 

362 """Parse setting value based on type.""" 

363 if not value: 

364 return None 

365 

366 try: 

367 if type_name in ("int", "integer"): 

368 return int(value) 

369 elif type_name in ("float", "number"): 

370 return float(value) 

371 elif type_name in ("bool", "boolean"): 

372 return value.lower() in ("true", "1", "yes", "on") 

373 elif type_name in ("list", "array"): 

374 return [item.strip() for item in value.split(",") if item.strip()] 

375 elif type_name in ("dict", "object"): 

376 return json.loads(value) 

377 

378 return value 

379 except (ValueError, json.JSONDecodeError): 

380 console.print( 

381 f"[red]Warning:[/red] Could not parse '{value}' as {type_name}, using as string" 

382 ) 

383 return value 

384 

385 async def _configure_global_settings(self, config: ConfigurationSchema) -> None: 

386 """Configure global settings.""" 

387 console.print("\n[bold]Global Settings:[/bold]") 

388 

389 if Confirm.ask("Configure global settings?"): 

390 # Common global settings 

391 settings_to_configure = [ 

392 ("debug", "bool", "Enable debug mode"), 

393 ("log_level", "str", "Logging level (DEBUG, INFO, WARNING, ERROR)"), 

394 ("secret_key", "str", "Application secret key"), 

395 ("database_url", "str", "Database connection URL"), 

396 ] 

397 

398 for setting_name, setting_type, description in settings_to_configure: 

399 if Confirm.ask(f"Configure {setting_name}?"): 

400 console.print(f"[dim]{description}[/dim]") 

401 value = Prompt.ask( 

402 setting_name, 

403 password=(setting_name in ("secret_key", "database_url")), 

404 ) 

405 config.global_settings[setting_name] = self._parse_setting_value( 

406 value, setting_type 

407 ) 

408 

409 def _display_validation_result(self, result: ConfigurationValidationResult) -> None: 

410 """Display configuration validation results.""" 

411 if result.status == ConfigurationStatus.VALID: 

412 console.print("[green]✓ Configuration is valid[/green]") 

413 elif result.status == ConfigurationStatus.WARNING: 

414 console.print("[yellow]⚠ Configuration has warnings[/yellow]") 

415 elif result.status == ConfigurationStatus.ERROR: 

416 console.print("[red]✗ Configuration has errors[/red]") 

417 

418 if result.errors: 

419 console.print("\n[red]Errors:[/red]") 

420 for error in result.errors: 

421 console.print(f" [red]•[/red] {error}") 

422 

423 if result.warnings: 

424 console.print("\n[yellow]Warnings:[/yellow]") 

425 for warning in result.warnings: 

426 console.print(f" [yellow]•[/yellow] {warning}") 

427 

428 

429# CLI Commands 

430 

431 

432@click.group() 

433def config_cli() -> None: 

434 """FastBlocks Configuration Management CLI.""" 

435 pass 

436 

437 

438@config_cli.command() 

439def wizard() -> None: 

440 """Launch the interactive configuration wizard.""" 

441 

442 async def _wizard() -> None: 

443 cli = InteractiveConfigurationCLI() 

444 await cli.initialize() 

445 await cli.run_configuration_wizard() 

446 

447 asyncio.run(_wizard()) 

448 

449 

450@config_cli.command() 

451@click.option( 

452 "--profile", 

453 type=click.Choice(["development", "staging", "production"]), 

454 default="development", 

455 help="Configuration profile", 

456) 

457@click.option("--adapters", help="Comma-separated list of adapters to include") 

458@click.option("--output", "-o", help="Output file path") 

459def create(profile: str, adapters: str | None, output: str | None) -> None: 

460 """Create a new configuration file.""" 

461 

462 async def _create() -> None: 

463 registry = AdapterRegistry() 

464 config_manager = ConfigurationManager(registry) 

465 await registry.initialize() 

466 await config_manager.initialize() 

467 

468 profile_enum = ConfigurationProfile(profile) 

469 adapter_list = adapters.split(",") if adapters else None 

470 

471 config = await config_manager.create_configuration( 

472 profile=profile_enum, adapters=adapter_list 

473 ) 

474 

475 config_file = await config_manager.save_configuration(config, output) 

476 console.print(f"[green]✓[/green] Configuration created: {config_file}") 

477 

478 asyncio.run(_create()) 

479 

480 

481def _format_json_output(result: ConfigurationValidationResult) -> None: 

482 """Format validation result as JSON.""" 

483 output = { 

484 "status": result.status.value, 

485 "errors": result.errors, 

486 "warnings": result.warnings, 

487 "adapter_results": result.adapter_results, 

488 } 

489 click.echo(json.dumps(output, indent=2)) 

490 

491 

492def _format_text_output(result: ConfigurationValidationResult) -> None: 

493 """Format validation result as human-readable text.""" 

494 # Print status 

495 status_messages = { 

496 ConfigurationStatus.VALID: "[green]✓ Configuration is valid[/green]", 

497 ConfigurationStatus.WARNING: "[yellow]⚠ Configuration has warnings[/yellow]", 

498 ConfigurationStatus.ERROR: "[red]✗ Configuration has errors[/red]", 

499 } 

500 console.print(status_messages.get(result.status, "Unknown status")) 

501 

502 # Print errors 

503 if result.errors: 

504 console.print("\n[red]Errors:[/red]") 

505 for error in result.errors: 

506 console.print(f" • {error}") 

507 

508 # Print warnings 

509 if result.warnings: 

510 console.print("\n[yellow]Warnings:[/yellow]") 

511 for warning in result.warnings: 

512 console.print(f" • {warning}") 

513 

514 

515@config_cli.command() 

516@click.argument("config_file") 

517@click.option("--format", type=click.Choice(["text", "json"]), default="text") 

518def validate(config_file: str, format: str) -> None: 

519 """Validate a configuration file.""" 

520 

521 async def _validate() -> None: 

522 registry = AdapterRegistry() 

523 config_manager = ConfigurationManager(registry) 

524 await registry.initialize() 

525 await config_manager.initialize() 

526 

527 try: 

528 config = await config_manager.load_configuration(config_file) 

529 result = await config_manager.validate_configuration(config) 

530 

531 # Format output based on requested format 

532 if format == "json": 

533 _format_json_output(result) 

534 else: 

535 _format_text_output(result) 

536 

537 except FileNotFoundError: 

538 console.print( 

539 f"[red]Error:[/red] Configuration file '{config_file}' not found" 

540 ) 

541 sys.exit(1) 

542 except Exception as e: 

543 console.print(f"[red]Error:[/red] {e}") 

544 sys.exit(1) 

545 

546 asyncio.run(_validate()) 

547 

548 

549@config_cli.command() 

550@click.argument("config_file") 

551@click.option("--output", "-o", help="Output .env file path") 

552def generate_env(config_file: str, output: str | None) -> None: 

553 """Generate .env file from configuration.""" 

554 

555 async def _generate_env() -> None: 

556 registry = AdapterRegistry() 

557 config_manager = ConfigurationManager(registry) 

558 await registry.initialize() 

559 await config_manager.initialize() 

560 

561 try: 

562 config = await config_manager.load_configuration(config_file) 

563 output_path = Path(output) if output else None 

564 env_file = await config_manager.generate_environment_file( 

565 config, output_path 

566 ) 

567 console.print(f"[green]✓[/green] Environment file created: {env_file}") 

568 except Exception as e: 

569 console.print(f"[red]Error:[/red] {e}") 

570 sys.exit(1) 

571 

572 asyncio.run(_generate_env()) 

573 

574 

575@config_cli.command() 

576def list_templates() -> None: 

577 """List available configuration templates.""" 

578 

579 async def _list_templates() -> None: 

580 registry = AdapterRegistry() 

581 config_manager = ConfigurationManager(registry) 

582 await config_manager.initialize() 

583 

584 templates_dir = config_manager.templates_dir 

585 if not templates_dir.exists(): 

586 console.print("[yellow]No templates directory found[/yellow]") 

587 return 

588 

589 templates = list(templates_dir.glob("*.yaml")) 

590 if not templates: 

591 console.print("[yellow]No templates available[/yellow]") 

592 return 

593 

594 console.print("[bold]Available Templates:[/bold]") 

595 for template in sorted(templates): 

596 console.print(f" • {template.stem}") 

597 

598 asyncio.run(_list_templates()) 

599 

600 

601@config_cli.command() 

602@click.argument("name") 

603@click.argument("description") 

604def backup(name: str, description: str) -> None: 

605 """Create a backup of current configuration.""" 

606 

607 async def _backup() -> None: 

608 # This would need to be implemented based on current active configuration 

609 console.print( 

610 "[yellow]Backup functionality needs active configuration context[/yellow]" 

611 ) 

612 

613 asyncio.run(_backup()) 

614 

615 

616@config_cli.command() 

617def list_backups() -> None: 

618 """List all configuration backups.""" 

619 

620 async def _list_backups() -> None: 

621 registry = AdapterRegistry() 

622 config_manager = ConfigurationManager(registry) 

623 await config_manager.initialize() 

624 

625 backups = await config_manager.list_backups() 

626 

627 if not backups: 

628 console.print("[yellow]No backups found[/yellow]") 

629 return 

630 

631 ServerPanels.backups_table(backups) 

632 

633 asyncio.run(_list_backups()) 

634 

635 

636@config_cli.command() 

637@click.argument("backup_id") 

638@click.option("--output", "-o", help="Output file path") 

639def restore(backup_id: str, output: str | None) -> None: 

640 """Restore configuration from backup.""" 

641 

642 async def _restore() -> None: 

643 registry = AdapterRegistry() 

644 config_manager = ConfigurationManager(registry) 

645 await config_manager.initialize() 

646 

647 try: 

648 config = await config_manager.restore_backup(backup_id) 

649 

650 if output: 

651 config_file = await config_manager.save_configuration(config, output) 

652 else: 

653 config_file = await config_manager.save_configuration(config) 

654 

655 console.print(f"[green]✓[/green] Configuration restored to: {config_file}") 

656 except Exception as e: 

657 console.print(f"[red]Error:[/red] {e}") 

658 sys.exit(1) 

659 

660 asyncio.run(_restore()) 

661 

662 

663if __name__ == "__main__": 

664 config_cli()