<?php

declare(strict_types=1);

$root = getenv('POC_APP_ROOT');
$dialect = getenv('POC_DIALECT');
$mainHost = getenv('POC_HOST');
$mainPort = (int)getenv('POC_PORT');
$mainSchema = getenv('POC_SCHEMA');
$mainUser = getenv('POC_USER');
$mainPassword = getenv('POC_PASSWORD');
$aiHost = getenv('POC_AI_HOST');
$aiPort = (int)getenv('POC_AI_PORT');
$aiSchema = getenv('POC_AI_SCHEMA');
$aiUser = getenv('POC_AI_USER');
$aiPassword = getenv('POC_AI_PASSWORD');
if (!$root || !in_array($dialect, ['mysql', 'dm'], true) || !$mainHost || $mainPort < 1 || !$mainSchema || !$mainUser || !$mainPassword
    || !$aiHost || $aiPort < 1 || !$aiSchema || !$aiUser || !$aiPassword) exit(2);
define('APP_PATH', $root . '/application/');
require $root . '/thinkphp/base.php';
require $root . '/application/common.php';
if (!function_exists('config')) {
    function config($name = '', $value = null, $range = '')
    {
        return $value === null ? \think\Config::get($name) : \think\Config::set($name, $value, $range);
    }
}

\think\Config::set([
    'type' => $dialect === 'dm' ? \app\cores\database\Dm::class : 'mysql',
    'hostname' => $mainHost,
    'hostport' => $mainPort,
    'database' => $mainSchema,
    'username' => $mainUser,
    'password' => $mainPassword,
    'prefix' => 'ydy_',
    'debug' => false,
    'resultset_type' => 'array',
    'fields_strict' => true,
    'auto_timestamp' => false,
    'ai_zhct' => [
        'hostname' => $aiHost,
        'hostport' => $aiPort,
        'database' => $aiSchema,
        'username' => $aiUser,
        'password' => $aiPassword,
        'prefix' => 'yoshop_',
    ],
], 'database');
\think\Db::clear();

$logic = new \app\p\logic\WalletFlow();
$results = [];
foreach (['cash', 'subsidy', 'gift', ''] as $accountType) {
    $result = $logic->getList([
        'start_date' => date('Y-m-d', strtotime('-7 days')),
        'end_date' => date('Y-m-d'),
        'account_type' => $accountType,
        'page' => 1,
        'page_size' => 3,
    ]);
    if (!isset($result['data'], $result['total'], $result['summary']) || count($result['data']) > 3
        || array_keys($result['summary']) !== ['total_inflow', 'total_outflow', 'net_change']) {
        throw new RuntimeException('Wallet flow result structure changed');
    }
    $results[$accountType === '' ? 'all' : $accountType] = ['total' => (int)$result['total'], 'rows_returned' => count($result['data'])];
}
$departments = $logic->departments();
if (!is_array($departments)) throw new RuntimeException('Department options unavailable');
$exportPath = sys_get_temp_dir() . '/codex-wallet-export-' . bin2hex(random_bytes(6)) . '.xlsx';
try {
    $export = $logic->exportToFile([
        'start_date' => date('Y-m-d'),
        'end_date' => date('Y-m-d'),
        'name' => '__CODEX_NO_SUCH_STAFF__',
    ], $exportPath);
    if ((int)($export['rows'] ?? -1) !== 0 || !is_file($exportPath)) {
        throw new RuntimeException('Empty wallet export did not produce a file');
    }
    $zip = new ZipArchive();
    if ($zip->open($exportPath) !== true || $zip->locateName('xl/worksheets/sheet1.xml') === false) {
        throw new RuntimeException('Wallet export is not a readable XLSX');
    }
    $zip->close();
} finally {
    if (is_file($exportPath)) unlink($exportPath);
}
$sample = $logic->getList([
    'start_date' => date('Y-m-d', strtotime('-7 days')),
    'end_date' => date('Y-m-d'),
    'account_type' => 'cash',
    'page' => 1,
    'page_size' => 1,
]);
$flowNo = (string)($sample['data'][0]['flow_no'] ?? '');
if ($flowNo === '') throw new RuntimeException('No cash-flow fixture for non-empty export');
$privateDir = sys_get_temp_dir() . '/codex-wallet-export-' . bin2hex(random_bytes(6));
if (!mkdir($privateDir, 0700)) throw new RuntimeException('Private export directory unavailable');
$nonemptyPath = $privateDir . '/wallet.xlsx';
try {
    $nonempty = $logic->exportToFile([
        'start_date' => date('Y-m-d', strtotime('-7 days')),
        'end_date' => date('Y-m-d'),
        'account_type' => 'cash',
        'keyword' => $flowNo,
    ], $nonemptyPath);
    if ((int)($nonempty['rows'] ?? 0) < 1 || !is_file($nonemptyPath)) {
        throw new RuntimeException('Non-empty wallet export did not produce rows');
    }
    $zip = new ZipArchive();
    if ($zip->open($nonemptyPath) !== true || $zip->locateName('xl/worksheets/sheet1.xml') === false) {
        throw new RuntimeException('Non-empty wallet export is not a readable XLSX');
    }
    $zip->close();
} finally {
    if (is_file($nonemptyPath)) unlink($nonemptyPath);
    rmdir($privateDir);
}
echo json_encode(['dialect' => $dialect, 'status' => 'passed', 'accounts' => $results,
    'department_options' => count($departments), 'xlsx_export' => 'passed',
    'nonempty_xlsx_export' => 'passed']) . PHP_EOL;
