<?php
declare(strict_types=1);

namespace Autogedal\FrontendI18n\Model;

class TranslationCsvReader
{
    /**
     * @return array<int,array{source:string,translation:string,raw_source:string,raw_translation:string,line:int}>
     */
    public function readRows(string $path): array
    {
        if (!is_file($path)) {
            throw new \InvalidArgumentException('Translation CSV not found: ' . $path);
        }

        $handle = fopen($path, 'rb');
        if ($handle === false) {
            throw new \RuntimeException('Unable to open translation CSV: ' . $path);
        }

        $rows = [];
        $line = 0;

        while (($row = fgetcsv($handle)) !== false) {
            $line++;
            if (count($row) < 2) {
                continue;
            }

            $source = trim((string)$row[0]);
            $translation = trim((string)$row[1]);
            if ($source === '') {
                continue;
            }

            $rows[] = [
                'source' => (string)$row[0],
                'translation' => (string)$row[1],
                'raw_source' => (string)$row[0],
                'raw_translation' => (string)$row[1],
                'line' => $line,
            ];
        }

        fclose($handle);

        return $rows;
    }

    /**
     * @param string[] $paths
     * @return array<string,string>
     */
    public function readMany(array $paths): array
    {
        $translations = [];

        foreach ($paths as $path) {
            foreach ($this->read($path) as $source => $target) {
                $translations[$source] = $target;
            }
        }

        return $translations;
    }

    /**
     * @return array<string,string>
     */
    public function read(string $path): array
    {
        $translations = [];
        foreach ($this->readRows($path) as $row) {
            $translations[$row['raw_source']] = $row['raw_translation'];
        }

        return $translations;
    }

    /**
     * @return array{total:int, translated:int, untranslated:int}
     */
    public function analyze(string $path): array
    {
        if (!is_file($path)) {
            return [
                'total' => 0,
                'translated' => 0,
                'untranslated' => 0,
            ];
        }

        $total = 0;
        $translated = 0;
        $untranslated = 0;

        foreach ($this->readRows($path) as $row) {
            $source = $row['raw_source'];
            $target = $row['raw_translation'];
            $total++;
            if ($target !== '' && $target !== $source) {
                $translated++;
                continue;
            }

            $untranslated++;
        }

        return [
            'total' => $total,
            'translated' => $translated,
            'untranslated' => $untranslated,
        ];
    }
}
