#!/usr/bin/php
<?php
require $_composer_autoload_path?? __DIR__.'/../vendor/autoload.php';

use nur\cli\Application;
use nur\file;
use nur\msg;
use nur\SL;
use nur\str;

Application::run(new class extends Application {
  const ARGS = [
    "merge" => parent::ARGS,
    "purpose" => "afficher la différence entre deux fichiers FSV",

    ["-k", "--hide-first", "value" => true],
  ];

  protected $hideFirst = false;
  protected $args;

  function main() {
    $files = [];
    foreach ($this->args as $arg) {
      if (is_file($arg)) {
        $files[] = $arg;
      } else {
        msg::warning("$arg: fichier invalide ou introuvable");
      }
    }
    $infs = [];
    $lines = [];
    foreach ($files as $file) {
      $infs[] = file::open($file, "rb");
      $lines[] = "";
    }
    while (SL::any_nz($lines)) {
      $lines = [];
      $maxsize = 0;
      foreach ($infs as $inf) {
        $line = fgets($inf);
        if ($line !== false) {
          $line = str::strip_nl($line);
          $size = strlen($line);
        } else {
          $size = 0;
        }
        if ($size > $maxsize) $maxsize = $size;
        $lines[] = $line;
      }
      $first = null;
      foreach ($lines as $line) {
        if ($first === null) {
          # afficher la première ligne
          $first = $line;
          if (!$this->hideFirst) {
            echo ">$first\n";
            continue;
          }
        }
        # afficher les différences entre la ligne courante et la première
        # ligne
        $diff = "";
        for ($i = 0; $i < $maxsize; $i++) {
          $firstc = substr($first, $i, 1);
          $curc = substr($line, $i, 1);
          if ($firstc !== $curc) $diff .= $curc;
          else $diff .= " ";
        }
        if (trim($diff) === "") {
          echo "=$diff\n";
        } else {
          echo "!$diff\n";
        }
      }
    }
    foreach ($infs as $inf) {
      file::close($inf);
    }
  }
});
