<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Business\MasterData\DberpChinaRegionDatasetReader;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Throwable;

/**
 * 维护人员从民政部页面刷新内置 database/data/china_divisions.json（生产导入不依赖外网）。
 */
class ExportDberpChinaRegionsDataCommand extends Command
{
    protected $signature = 'dberp:regions:export-china-data
                            {--url= : 覆盖民政部源页面地址，默认读取 config/dberp.php}
                            {--output= : 输出 JSON 路径，默认 database/data/china_divisions.json}';

    protected $description = '从民政部页面抓取省市区县并写入项目内置 JSON 数据文件（开发维护用）';

    public function handle(DberpChinaRegionDatasetReader $reader): int
    {
        $sourceUrl = (string) ($this->option('url') ?: config('dberp.regions.china_import.source_url', ''));

        if ($sourceUrl === '') {
            $this->components->error('未配置民政部源地址。请在 config/dberp.php 设置 source_url 或通过 --url 传入。');

            return self::FAILURE;
        }

        $this->components->info('正在拉取民政部页面：'.$sourceUrl);

        try {
            $html = Http::timeout(60)
                ->connectTimeout(15)
                ->retry(3, 500)
                ->get($sourceUrl)
                ->throw()
                ->body();

            $rows = $reader->parseHtmlRows($html);
            $path = $reader->writeRowsToFile($rows, $this->option('output') ? (string) $this->option('output') : null);
        } catch (Throwable $throwable) {
            $this->components->error('导出失败：'.$throwable->getMessage());

            return self::FAILURE;
        }

        $this->components->info('已写入 '.count($rows).' 条记录到：'.$path);

        return self::SUCCESS;
    }
}
