<?php
// app/services/metadata/OmdbProvider.php

declare(strict_types=1);

namespace ScMedia\Services\Metadata;

use ScMedia\Services\HttpClient;
use ScMedia\Services\LogService;

final class OmdbProvider implements MetadataProvider {
  private HttpClient $http;
  private ?LogService $logger;

  public function __construct(HttpClient $http, ?LogService $logger = null) {
    $this->http = $http;
    $this->logger = $logger;
  }

  public function id(): string {
    return 'omdb';
  }

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

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

  public function buildUrl(string $externalId): string {
    return $externalId !== '' ? ('https://www.imdb.com/title/' . $externalId) : '';
  }

  public function search(string $query, string $type, ?int $year, string $lang, array $config): array {
    $apiKey = (string)($config['api_key'] ?? '');
    if ($apiKey === '') {
      $this->logger?->log('warn', 'OMDb API key missing');
      return [];
    }
    $base = (string)($config['base_url'] ?? 'https://www.omdbapi.com/');
    $q = [
      'apikey' => $apiKey,
      's' => $query,
    ];
    if ($type !== '') {
      $q['type'] = $type;
    }
    if ($year !== null && $year > 1800 && $year < 2100) {
      $q['y'] = (string)$year;
    }
    $url = rtrim($base, '/') . '/?' . http_build_query($q);
    $this->logger?->log('debug', 'OMDb request', ['url' => $this->sanitizeUrl($url)]);
    $res = $this->http->getJson($url);
    if (empty($res['ok']) || !is_array($res['data'])) {
      $this->logger?->log('error', 'OMDb request failed', [
        'status' => $res['status'] ?? null,
        'error' => $res['error'] ?? null,
      ]);
      return [];
    }
    $data = $res['data'];
    if (!empty($data['Response']) && $data['Response'] === 'False') {
      $this->logger?->log('warn', 'OMDb response false', ['error' => $data['Error'] ?? null]);
      return [];
    }
    $items = is_array($data['Search'] ?? null) ? $data['Search'] : [];
    $out = [];
    foreach ($items as $it) {
      if (!is_array($it)) continue;
      $id = (string)($it['imdbID'] ?? '');
      $title = (string)($it['Title'] ?? '');
      $yearStr = (string)($it['Year'] ?? '');
      $yr = null;
      if (preg_match('/\d{4}/', $yearStr, $m)) {
        $yr = (int)$m[0];
      }
      $poster = (string)($it['Poster'] ?? '');
      if ($poster === 'N/A') $poster = '';
      $out[] = [
        'provider' => $this->id(),
        'provider_name' => $this->label(),
        'provider_id' => $id,
        'provider_url' => $this->buildUrl($id),
        'title_map' => [$lang => $title],
        'original_title' => $title,
        'year' => $yr,
        'poster' => $poster,
        'type' => (string)($it['Type'] ?? $type),
      ];
    }
    return $out;
  }

  private function sanitizeUrl(string $url): string {
    $debugKeys = filter_var(getenv('DEBUG_KEYS') ?: 'false', FILTER_VALIDATE_BOOLEAN);
    if ($debugKeys) return $url;
    return preg_replace('/apikey=[^&]+/i', 'apikey=DUMMY', $url) ?? $url;
  }
}
