<?php

declare(strict_types=1);

namespace PpPhp\Core\DataOps\Readers;

use PpPhp\Core\DataOps\ImportReader;

/**
 * JSON — an array of objects (the shape JsonFormat exports), or an array of
 * arrays. Object keys become the header so auto-mapping works immediately.
 */
final class JsonReader implements ImportReader
{
    public static function id(): string { return 'json'; }
    public static function label(): string { return 'JSON'; }
    public static function extensions(): array { return ['json']; }
    public static function supportsPaste(): bool { return true; }

    public function read(string $path, array $opts): array
    {
        $data = json_decode((string) @file_get_contents($path), true);
        if (!is_array($data)) return [[], []];
        // Unwrap a single wrapper key: {"records":[…]}
        if ($data !== [] && !array_is_list($data)) {
            foreach ($data as $v) { if (is_array($v) && array_is_list($v)) { $data = $v; break; } }
        }
        if (!is_array($data) || !array_is_list($data)) return [[], []];

        $header = [];
        foreach ($data as $item) {
            if (is_array($item) && !array_is_list($item)) {
                foreach (array_keys($item) as $k) $header[(string) $k] = true;
            }
        }
        $header = array_keys($header);
        $rows = [];
        foreach ($data as $item) {
            if (!is_array($item)) continue;
            if ($header !== []) {
                $row = [];
                foreach ($header as $k) {
                    $v = $item[$k] ?? '';
                    $row[] = is_scalar($v) || $v === null ? (string) $v : json_encode($v);
                }
                $rows[] = $row;
            } else {
                $rows[] = array_map(static fn($v) => is_scalar($v) || $v === null ? (string) $v : json_encode($v), array_values($item));
            }
        }
        if ($header === [] && $rows) $header = array_map(static fn($i) => 'Column ' . ($i + 1), array_keys($rows[0]));
        return [$header, $rows];
    }
}
