<?php

declare(strict_types=1);

// One-shot pure PDO reproduction of the three generated synthetic SQL statements.
// No framework, business table, write, or custom PDOStatement subclass.
$phase = 'preflight';
try {
    if (!defined('PDO::EXTRA_DECIMAL')) {
        throw new RuntimeException('Candidate driver required');
    }
    foreach (['HOST', 'PORT', 'SCHEMA', 'USER', 'PASSWORD'] as $part) {
        if ((string) getenv('POC_AI_' . $part) === '') {
            throw new RuntimeException('Approved AI runtime environment required');
        }
    }
    $dsn = 'dm:host=' . getenv('POC_AI_HOST') . ';port=' . getenv('POC_AI_PORT')
        . ';schema=' . getenv('POC_AI_SCHEMA');
    $pdo = new PDO($dsn, (string) getenv('POC_AI_USER'),
        (string) getenv('POC_AI_PASSWORD'), [
            PDO::ATTR_CASE => PDO::CASE_LOWER,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_STRINGIFY_FETCHES => true,
            PDO::EXTRA_DECIMAL => 1,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ]);
    $raw = "SELECT 7 AS I,CAST('9007199254740993.01' AS DECIMAL(30,2)) AS D,"
        . "CAST('0.00' AS DECIMAL(5,2)) AS Z FROM DUAL";
    $queries = [
        'query' => [$raw, []],
        'find' => ['SELECT * FROM (' . $raw
            . ') EXACT_Q WHERE  i = :ThinkBind_1_166812837_ LIMIT 1  ',
            [[':ThinkBind_1_166812837_', 7, PDO::PARAM_STR]]],
        'select' => ['SELECT * FROM (' . $raw . ') EXACT_Q ', []],
    ];
    foreach ($queries as $phase => $entry) {
        fwrite(STDERR, 'PDO_BEGIN ' . $phase . PHP_EOL);
        // Same lifecycle as PDOConnection::getPDOStatement + getResult:
        // a fresh prepare overwrites the previous PDOStatement, then fetchAll.
        $statement = $pdo->prepare($entry[0]);
        foreach ($entry[1] as $bind) {
            $statement->bindValue($bind[0], $bind[1], $bind[2]);
        }
        $statement->execute();
        $rows = $statement->fetchAll(PDO::FETCH_ASSOC);
        $types = [];
        foreach ($rows[0] ?? [] as $name => $value) {
            $types[$name] = gettype($value);
        }
        fwrite(STDERR, 'PDO_DONE ' . $phase . ' rows=' . count($rows)
            . ' field_types=' . json_encode($types) . PHP_EOL);
    }
    echo json_encode(['php' => PHP_VERSION, 'status' => 'pass',
        'business_writes' => 0, 'driver' => 'candidate_paired']) . PHP_EOL;
} catch (Throwable $error) {
    echo json_encode(['php' => PHP_VERSION, 'status' => 'fail',
        'phase' => $phase, 'error_class' => get_class($error),
        'error_code' => $error->getCode()]) . PHP_EOL;
    exit(1);
}
