<?php

namespace Drupal\artisan;

/**
 * Allows interacting with the vite manifest.
 */
class ArtisanManifest {

  /**
   * Vite manifest.
   *
   * @var array
   */
  protected $manifest;

  public function __construct(protected string $themePath) {
    $this->initManifest($this->themePath);
  }

  /**
   * Init vite manifest.
   */
  protected function initManifest(string $theme_path):void {
    $path = sprintf('%s/dist/.vite/manifest.json', $theme_path);
    if (file_exists($path)) {
      $this->manifest = json_decode((string) file_get_contents($path), TRUE) ?? [];
    }
    else {
      $this->manifest = [];
    }
  }

  /**
   * Get Vite manifest.
   *
   * @return array
   *   Manifest data.
   */
  public function raw():array {
    return $this->manifest;
  }

  /**
   * Get the source files for a list of destination files.
   *
   * @param array $destination_files
   *   The list of destination files.
   */
  public function getSourceFiles(array $destination_files) {
    $raw = $this->raw();

    $destination_files = array_map(function ($file) {
      return str_replace($this->themePath . '/dist/', '', $file);
    }, $destination_files);

    $sources = [];
    foreach ($raw as $source => $info) {
      $destination = $info['file'] ?? NULL;

      if (in_array($destination, $destination_files)) {
        $sources[] = $this->themePath . '/' . $source;
      }
    }
    return array_filter($sources, 'file_exists');
  }

}
