<?php
/**
 * 审计各渠道游戏配置是否已从默认模板实例化
 * 用法：php server/db/audit_channel_config.php [--fix]
 */
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../support/bootstrap.php';

use app\dice\helper\AdminScopeHelper;
use app\dice\service\DiceChannelConfigService;
use plugin\saiadmin\app\model\system\SystemDept;
use support\think\Db;

$fix = in_array('--fix', $argv ?? [], true);
$templateId = AdminScopeHelper::DEFAULT_TEMPLATE_DEPT;
$tables = [
    'dice_config',
    'dice_ante_config',
    'dice_lottery_pool_config',
    'dice_reward_config',
    'dice_game',
    'dice_reward',
];

$templateCounts = [];
foreach ($tables as $table) {
    $templateCounts[$table] = (int) Db::table($table)
        ->where(function ($q) use ($templateId) {
            $q->where('dept_id', $templateId)->whereOr('dept_id', null);
        })
        ->count();
}

$depts = SystemDept::where('id', '>', 0)->column('id');
echo "========== 渠道配置实例化审计 ==========\n";
echo "默认模板 dept_id={$templateId} 行数：\n";
foreach ($templateCounts as $table => $cnt) {
    echo "  {$table}: {$cnt}\n";
}
echo "\n";

$missing = [];
foreach ($depts as $deptId) {
    $deptId = (int) $deptId;
    if ($deptId <= 0) {
        continue;
    }
    $issues = [];
    foreach ($tables as $table) {
        $expected = $templateCounts[$table];
        if ($expected <= 0) {
            continue;
        }
        $actual = (int) Db::table($table)->where('dept_id', $deptId)->count();
        if ($actual < $expected) {
            $issues[] = "{$table}: {$actual}/{$expected}";
        }
    }
    if ($issues !== []) {
        $missing[$deptId] = $issues;
        echo "渠道 {$deptId} 不完整 → " . implode(', ', $issues) . "\n";
    } else {
        echo "渠道 {$deptId} OK\n";
    }
}

if ($missing === []) {
    echo "\n全部渠道配置已实例化。\n";
    exit(0);
}

if (!$fix) {
    echo "\n存在缺失。执行 php server/db/audit_channel_config.php --fix 可自动补齐。\n";
    exit(1);
}

echo "\n开始补齐...\n";
$service = new DiceChannelConfigService();
$summary = $service->syncAllChannelsFromDefault();
foreach ($summary as $deptId => $info) {
    $copied = implode(',', $info['copied_tables'] ?? []);
    echo "渠道 {$deptId}: 新增表 [{$copied}] 补齐行 " . ($info['merged_rows'] ?? 0) . "\n";
}
echo "补齐完成，请重新运行审计确认。\n";
