<?php
// app/controllers/tools.php

declare(strict_types=1);

use ScMedia\Http\Response;
use ScMedia\Http\Router;

final class ToolsController extends BaseController {
  public static function register(Router $router, Container $container): void {
    $self = new self($container);
    $router->add('POST', '/api/tools/test-path', fn() => $self->testPath());
    $router->add('GET', '/api/tools/detect-binaries', fn() => $self->detectBinaries());
  }

  private function testPath(): void {
    $logger = $this->logger();
    $body = read_json_body();
    $path = (string)($body['path'] ?? '');
    $checks = is_array($body['checks'] ?? null) ? $body['checks'] : ['exists','read','write','rename'];
    $data = $this->services()['path_tool']->testPath($path, $checks);
    $logger->log('info', 'Path test', ['path' => $path, 'checks' => $checks, 'results' => $data['results'] ?? null, 'notes' => $data['notes'] ?? null]);
    Response::json(['ok' => true, 'data' => ['path' => $path] + $data]);
  }

  private function detectBinaries(): void {
    $logger = $this->logger();
    $shell = $this->services()['shell'] ?? null;
    $bins = ['mkvmerge', 'mkvpropedit', 'ffmpeg'];
    $out = [];
    foreach ($bins as $b) {
      $out[$b . '_path'] = ($shell instanceof \ScMedia\Services\ShellTool) ? $shell->which($b) : null;
    }
    $logger->log('info', 'Detect binaries', ['binaries' => $out]);
    Response::json(['ok' => true, 'data' => $out]);
  }
}
