<?php
declare(strict_types=1);
namespace App\Admin;
use InvalidArgumentException;
final class SeedImportService
{
    /** @return array{valid:int,invalid:int,rows:list<array<string,mixed>>,errors:list<string>} */
    public function previewJson(string $json):array
    {
        if(strlen($json)>2*1024*1024)throw new InvalidArgumentException('Seed JSON is too large.');$data=json_decode($json,true,64);if(!is_array($data))throw new InvalidArgumentException('Seed JSON is invalid.');return $this->previewRows(array_is_list($data)?$data:[$data]);
    }
    /** @return array{valid:int,invalid:int,rows:list<array<string,mixed>>,errors:list<string>} */
    public function previewCsv(string $csv):array
    {
        if(strlen($csv)>2*1024*1024)throw new InvalidArgumentException('Seed CSV is too large.');$fh=fopen('php://temp','w+');fwrite($fh,$csv);rewind($fh);$headers=fgetcsv($fh);if(!is_array($headers))throw new InvalidArgumentException('Seed CSV is empty.');$rows=[];while(($values=fgetcsv($fh))!==false){$row=[];foreach($headers as $i=>$h)$row[trim((string)$h)]=$values[$i]??'';$rows[]=$row;}fclose($fh);return $this->previewRows($rows);
    }
    /** @param array<int,mixed> $rows @return array{valid:int,invalid:int,rows:list<array<string,mixed>>,errors:list<string>} */
    public function previewRows(array $rows):array
    {
        $safe=[];$errors=[];$valid=0;$invalid=0;$allowed=['persona','persona_id','type','title','body','question_id','category','category_id','tags','tag_ids','locale','kind','status'];
        foreach($rows as $i=>$row){if(!is_array($row)){$invalid++;$errors[]='Row '.($i+1).' is not an object.';continue;}$clean=[];foreach($allowed as $key)if(array_key_exists($key,$row))$clean[$key]=$row[$key];$type=strtolower(trim((string)($clean['type']??'')));$body=trim((string)($clean['body']??''));$title=trim((string)($clean['title']??''));$persona=trim((string)($clean['persona']??$clean['persona_id']??''));$ok=in_array($type,['question','answer','topic'],true)&&$body!==''&&$persona!==''&&($type==='answer'||$title!=='');if($ok){$valid++;$safe[]=$clean;}else{$invalid++;$errors[]='Row '.($i+1).' is missing persona/type/title/body requirements.';}}
        return ['valid'=>$valid,'invalid'=>$invalid,'rows'=>$safe,'errors'=>$errors];
    }
}
