<?php

namespace App\Console\Commands;

use App\Support\JudgeCardTemplateBuilder;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class GenerateJudgeCardTemplateCommand extends Command
{
    protected $signature = 'exam:generate-judge-card-template {--path= : 输出文件路径，默认项目根目录 judge_card.template.json}';

    protected $description = '根据判卷卡排版参数生成 Python 识别模板 JSON';

    public function handle(JudgeCardTemplateBuilder $builder): int
    {
        $outputPath = (string) ($this->option('path') ?: base_path('judge_card.template.json'));
        $directory = dirname($outputPath);

        if (! is_dir($directory)) {
            File::ensureDirectoryExists($directory);
        }

        $template = $builder->build();
        $json = json_encode($template, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        if ($json === false) {
            $this->error('生成 judge_card.template.json 失败：JSON 编码错误');

            return self::FAILURE;
        }

        File::put($outputPath, $json.PHP_EOL);
        $this->info("判卷卡模板已生成：{$outputPath}");

        return self::SUCCESS;
    }
}

