<?php

namespace App\Console\Commands;

use App\Services\PromptService;
use Illuminate\Console\Command;

class ImportPromptTemplates extends Command
{
    protected $signature = 'prompt:import {file : 导出的提示词 JSON 文件路径}';

    protected $description = '从导出的 JSON 文件导入提示词到 MySQL';

    public function handle(): int
    {
        $path = (string) $this->argument('file');
        if (!is_file($path)) {
            $this->error('文件不存在: ' . $path);
            return self::FAILURE;
        }

        $content = file_get_contents($path);
        $payload = json_decode($content ?: '[]', true);
        if (!is_array($payload)) {
            $this->error('JSON 解析失败');
            return self::FAILURE;
        }

        $result = app(PromptService::class)->importFromArray($payload);
        $this->info(sprintf('导入 %d，更新 %d', $result['imported'] ?? 0, $result['updated'] ?? 0));

        if (!empty($result['errors'])) {
            $this->warn('部分失败：' . implode('；', $result['errors']));
        }

        return self::SUCCESS;
    }
}
