<?php
declare(strict_types=1);

// One owned active coupon, one read-only HTTP route, exact independent cleanup.
$phase = (string)($argv[1] ?? '');
$lane = (string)($argv[2] ?? '');
$marker = (string)($argv[3] ?? '');
if (!in_array($phase, ['--schema', '--audit', '--run'], true)
    || !in_array($lane, ['B', 'C'], true)
    || !preg_match('/^CDXCL[A-F0-9]{12}$/D', $marker)
    || ($phase === '--run' && getenv('CDX_COUPON_LIST_RUN') !== 'ONE_OWNED_ACTIVE_COUPON_V1')) {
    fwrite(STDERR, "DENIED business_http=0 business_dml=0\n");
    exit(78);
}
if ($lane === 'B') {
    $cfg = parse_ini_file('/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api/.env.local',
        true, INI_SCANNER_RAW)['DATABASE'] ?? null;
    if (!is_array($cfg) || strtolower((string)($cfg['TYPE'] ?? '')) !== 'mysql'
        || (string)($cfg['HOSTPORT'] ?? '') !== '3306'
        || hash('sha256', (string)($cfg['HOSTNAME'] ?? ''))
            !== '47e8be48b0cfd56dcdb9d9d426e6637b245f340b4efad4cd2f084ec5851ecc8e'
        || hash('sha256', (string)($cfg['DATABASE'] ?? ''))
            !== 'cf7756b3bb52cf72f625689134015b877fdab3ad8eb3bb2ddd962bb35f6efd66') {
        throw new RuntimeException('B code-local development MySQL identity drift');
    }
    $db = new PDO('mysql:host=' . $cfg['HOSTNAME'] . ';port=3306;dbname=' . $cfg['DATABASE']
        . ';charset=' . $cfg['CHARSET'], $cfg['USERNAME'], $cfg['PASSWORD'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_LOWER]);
    $port = 18101;
} else {
    if (getenv('POC_DIALECT') !== 'dm' || getenv('POC_AI_HOST') !== '127.0.0.1'
        || getenv('POC_AI_PORT') !== '5238' || getenv('POC_AI_SCHEMA') !== 'AIZHCT_APP'
        || getenv('POC_AI_USER') !== 'AIZHCT_APP') {
        throw new RuntimeException('C isolated AI DM worker identity drift');
    }
    $db = new PDO('dm:host=127.0.0.1;port=5238;schema=AIZHCT_APP',
        getenv('POC_AI_USER'), getenv('POC_AI_PASSWORD'),
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_LOWER]);
    if ($db->query("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")
        ->fetchColumn() !== 'AIZHCT_APP') {
        throw new RuntimeException('C effective schema drift');
    }
    $port = 18102;
}
$select = static function (string $sql, array $args = []) use ($db): array {
    $stmt = $db->prepare($sql);
    $stmt->execute($args);
    return array_map(static function (array $row): array {
        return array_change_key_case($row, CASE_LOWER);
    }, $stmt->fetchAll(PDO::FETCH_ASSOC));
};
$own = static function () use ($select, $marker): array {
    return $select('SELECT coupon_id,name,coupon_type,reduce_price,min_price,expire_type,'
        . 'start_time,end_time,total_num,receive_num,status,is_delete,store_id'
        . ' FROM yoshop_coupon WHERE name=? AND store_id=10001', [$marker]);
};
if ($phase === '--schema') {
    $sql = $lane === 'B'
        ? "SELECT column_name,data_type,is_nullable FROM information_schema.columns"
            . " WHERE table_schema=DATABASE() AND table_name='yoshop_coupon' ORDER BY ordinal_position"
        : "SELECT column_name,data_type,nullable AS is_nullable FROM user_tab_columns"
            . " WHERE table_name='YOSHOP_COUPON' ORDER BY column_id";
    $cols = $select($sql);
    echo json_encode(['lane' => $lane, 'phase' => 'schema', 'columns' => $cols,
        'business_http' => 0, 'business_dml' => 0], JSON_UNESCAPED_SLASHES), PHP_EOL;
    exit(count($cols) >= 21 ? 0 : 2);
}
if ($phase === '--audit') {
    echo json_encode(['lane' => $lane, 'phase' => 'audit',
        'owned_coupon_count' => count($own()), 'business_http' => 0, 'business_dml' => 0]), PHP_EOL;
    exit($own() ? 2 : 0);
}
if ($own()) throw new RuntimeException('coupon marker already exists');
$activeCount = static function () use ($db): int {
    return (int)$db->query('SELECT COUNT(*) FROM yoshop_coupon'
        . ' WHERE store_id=10001 AND status=1 AND is_delete=0')->fetchColumn();
};
$sourceBefore = $activeCount();
$result = [];
$error = null;
try {
    $now = time();
    $describeColumn = $lane === 'B' ? '`describe`' : '"DESCRIBE"';
    $insert = $db->prepare('INSERT INTO yoshop_coupon'
        . ' (name,coupon_type,reduce_price,discount,min_price,expire_type,expire_day,'
        . 'start_time,end_time,apply_range,apply_range_config,total_num,receive_num,'
        . $describeColumn . ',status,sort,is_delete,store_id,create_time,update_time)'
        . ' VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
    $insert->execute([$marker, 10, '12.34', 0, '56.78', 20, 0,
        $now - 86400, $now + 86400, 10, '[]', 10, 0,
        'CDX compatibility test only', 1, 0, 0, 10001, $now, $now]);
    $rows = $own();
    if (count($rows) !== 1 || (int)$rows[0]['status'] !== 1
        || (int)$rows[0]['is_delete'] !== 0 || (int)$rows[0]['store_id'] !== 10001
        || (int)$rows[0]['coupon_type'] !== 10
        || bccomp((string)$rows[0]['reduce_price'], '12.34', 2) !== 0
        || bccomp((string)$rows[0]['min_price'], '56.78', 2) !== 0) {
        throw new RuntimeException('owned coupon original row invalid');
    }
    if ($activeCount() !== $sourceBefore + 1) {
        throw new RuntimeException('active coupon source delta is not one');
    }
    $ctx = stream_context_create(['http' => ['method' => 'GET',
        'header' => "platform: H5\r\n", 'ignore_errors' => true,
        'follow_location' => 0, 'timeout' => 20]]);
    $handle = @fopen('http://127.0.0.1:' . $port . '/api/Coupon/list?storeId=10001',
        'rb', false, $ctx);
    if (!is_resource($handle)) throw new RuntimeException('isolated AI Coupon/list HTTP unavailable');
    $transportLine = (string)($http_response_header[0] ?? '');
    $raw = stream_get_contents($handle, 1048577);
    fclose($handle);
    if (!preg_match('~^HTTP/\S+ 200(?: |$)~', $transportLine)) {
        throw new RuntimeException('Coupon/list transport status not 200');
    }
    if (!is_string($raw) || strlen($raw) > 1048576) throw new RuntimeException('coupon response cap');
    $body = json_decode($raw, true);
    if (!is_array($body) || (int)($body['status'] ?? 0) !== 200
        || !is_array($body['data']['list'] ?? null)) {
        throw new RuntimeException('Coupon/list business response failed: '
            . (string)($body['status'] ?? 'nonjson'));
    }
    $list = $body['data']['list'];
    $matched = array_values(array_filter($list, static function ($item) use ($rows): bool {
        return is_array($item) && (int)($item['coupon_id'] ?? 0) === (int)$rows[0]['coupon_id'];
    }));
    if (count($matched) !== 1 || ($matched[0]['name'] ?? null) !== $marker
        || (int)($matched[0]['coupon_type'] ?? 0) !== 10
        || bccomp((string)($matched[0]['reduce_price'] ?? ''), '12.34', 2) !== 0
        || bccomp((string)($matched[0]['min_price'] ?? ''), '56.78', 2) !== 0
        || ($matched[0]['state']['text'] ?? null) !== '正常'
        || (int)($matched[0]['state']['value'] ?? 0) !== 1) {
        throw new RuntimeException('owned coupon HTTP row/source contract mismatch');
    }
    $shape = static function ($value) use (&$shape) {
        if (!is_array($value)) return gettype($value);
        $result = [];
        foreach ($value as $key => $item) $result[(string)$key] = $shape($item);
        ksort($result);
        return $result;
    };
    $types = $shape($matched[0]);
    $result = ['lane' => $lane, 'http_transport_status' => 200, 'business_http_ok' => 1,
        'source_before_count' => $sourceBefore,
        'source_with_owned_count' => $sourceBefore + 1,
        'http_list_count' => count($list),
        'own_row_types' => $types,
        'own_row_type_sha256' => hash('sha256', json_encode($types)),
        'source_owned_coupon_equal' => true];
} catch (Throwable $caught) {
    $error = $caught;
} finally {
    foreach ($own() as $row) {
        $delete = $db->prepare('DELETE FROM yoshop_coupon'
            . ' WHERE coupon_id=? AND name=? AND store_id=10001');
        $delete->execute([(int)$row['coupon_id'], $marker]);
    }
}
if ($own() || $activeCount() !== $sourceBefore) {
    throw new RuntimeException('owned coupon cleanup or natural active count failed');
}
if ($error !== null) throw $error;
$result['owned_coupon_cleanup_zero'] = true;
$result['external_payment_oss_queue'] = 0;
echo json_encode($result, JSON_UNESCAPED_SLASHES), PHP_EOL;
