<?php
// app/services/export/JellyfinExporter.php

declare(strict_types=1);

namespace ScMedia\Services\Export;

final class JellyfinExporter implements ExporterInterface {
  public function id(): string {
    return 'jellyfin';
  }

  public function label(): string {
    return 'Jellyfin';
  }

  public function supportsKind(string $kind): bool {
    return in_array($kind, ['movie','series'], true);
  }

  public function exportMovie(string $filePath, array $meta): array {
    $dir = dirname($filePath);
    $outPath = $dir . '/movie.nfo';
    return $this->writeNfo($outPath, 'movie', $meta);
  }

  public function exportSeries(string $seriesPath, array $meta): array {
    $outPath = rtrim($seriesPath, '/') . '/tvshow.nfo';
    return $this->writeNfo($outPath, 'tvshow', $meta);
  }

  private function writeNfo(string $path, string $root, array $meta): array {
    $title = (string)($meta['title'] ?? '');
    $original = (string)($meta['original_title'] ?? '');
    $year = $meta['year'] ?? null;
    $provider = (string)($meta['provider'] ?? '');
    $providerId = (string)($meta['provider_id'] ?? '');
    $providerUrl = (string)($meta['provider_url'] ?? '');

    $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    $xml .= "<{$root}>\n";
    if ($title !== '') $xml .= "  <title>" . htmlspecialchars($title, ENT_QUOTES) . "</title>\n";
    if ($original !== '') $xml .= "  <originaltitle>" . htmlspecialchars($original, ENT_QUOTES) . "</originaltitle>\n";
    if (is_int($year) || is_numeric($year)) $xml .= "  <year>" . (int)$year . "</year>\n";
    if ($provider !== '' && $providerId !== '') {
      $xml .= "  <uniqueid type=\"" . htmlspecialchars($provider, ENT_QUOTES) . "\" default=\"true\">" .
        htmlspecialchars($providerId, ENT_QUOTES) . "</uniqueid>\n";
    }
    if ($providerUrl !== '') {
      $xml .= "  <website>" . htmlspecialchars($providerUrl, ENT_QUOTES) . "</website>\n";
    }
    $xml .= "</{$root}>\n";

    $ok = @file_put_contents($path, $xml) !== false;
    return ['ok' => $ok, 'path' => $path, 'error' => $ok ? null : 'write failed'];
  }
}
