#!/usr/bin/env python3
"""Readable complete SQL/case/binding/oracle view, stdout only."""
import hashlib
import json
from pathlib import Path
R = Path(__file__).resolve().parent


def render(p):
    lines = ['# C-only literal nearest-even proposal — NOT EXECUTED', '',
      'Frozen machine plan: `proposal.json`; SHA256 `' + hashlib.sha256((R/'proposal.json').read_bytes()).hexdigest() + '`.', '',
      'Reuses all 43 distinct original lexemes from the sealed B five-column/half-tie probes; no new input vectors. Four OS sentinels repeat existing values, not new vectors. All original bytes remain unchanged.', '',
      '## Budget / execution order', '',
      'C only: 2 identity SELECTs + 47 literal SELECTs = **49 executed SELECTs**; 1 prepare-only attempt, **50 diagnostic attempts total ≤64**. No retry. DDL0/DML0/natural0/HTTP0/B SQL0/transaction calls0. Each identity-schema/literal result exactly1 row; V$VERSION≤16 rows; each serialized result≤65536 bytes. Identity/prepare failure stops before literal executions; a later SQL/type/row/bytes failure stops this sequence without retry.', '',
      'Order: identity_schema once → identity_version once → prepare-only literal_rint once → cases below in order. All identity bindings empty; each literal has exactly the sole positional binding below. No business tables, dependencies or cleanup DDL exist in this plan.', '',
      '## Connection and evidence', '',
      'Only original C worker112175: first cmdline must identify `/tmp/zhct-dm-poc-20260928.fcpiiN/store`; then read only its approved environment subset, isolated-scope require original `application/database.php`, assert exact127.0.0.1:5237/ZHCT_APP. Fresh nonpersistent PDO, existing PHP73 with both original DM extensions. No driver/config/charset/sql_mode setter. No entire env or secret values logged.', '',
      'Environment whitelist: `' + '`, `'.join(p['connection']['env_whitelist']) + '`.', '',
      'Persist original statement/errorInfo, unchanged typed parameters, native type/value, float17g, native-double HEX/byte order, and column metadata. C warnings remain unknown. Query only exact three frozen SQL strings; WITH is not a generic allowlist.', '',
      '## Unique exact SQL templates', '']
    for name, sql in p['templates'].items():
        lines += ['### '+name, '', 'SHA256 `' + hashlib.sha256(sql.encode()).hexdigest() + '`; binds ' + ('1' if name=='literal_rint' else '0') + '.', '', '```sql', sql, '```', '']
    lines += ['## Binding rules and all case mappings', '',
      '`S`: original string → runtime same string, PHP string/PDO::PARAM_STR(2). `OS`: original string → runtime same string, PHP string/PDO::PARAM_INT(1), never truncate or preconvert. `NULL`: original/runtime null, PHP NULL/PDO::PARAM_NULL(0). Position1; no other bindings, pre-round, or host numeric conversion.', '',
      'Oracle values are strings, never JSON floating numbers. Stored hex=`STORED_DOUBLE` expectation; getter hex=separate physical-FLOAT(8,2) final-format expectation, **not** SQL STORED_DOUBLE. Old stored oracle comes from original decimal30 parsed-back double, not physical DB bits; half-tie oracle comes from actual computed-column native-double bits. Both use original raw journals. NULL remains NULL.', '',
      '| Ordered case | Template / bind | Pos1 original = runtime | Oracle index | Stored promoted-double HEX | Physical getter HEX | Stored oracle provenance |',
      '| --- | --- | --- | ---: | --- | --- | --- |']
    for c in p['cases']:
        o = p['oracles'][c['oracle_index']]
        preferred = o['preferred_stored_oracle']
        kind = 'actual-half-native' if preferred['kind'].startswith('half_') else 'old-decimal30-roundtrip'
        lex = json.dumps(c['parameters'][0]['original_value'], ensure_ascii=False)
        rule = 'NULL' if c['parameters'][0]['original_value'] is None else ('OS' if c['case_id'].startswith('OS-') else 'S')
        hx = lambda v: 'NULL' if v is None else '`'+v+'`'
        lines.append('| '+c['case_id']+' | literal_rint / '+rule+' | `'+lex+'` | '+str(c['oracle_index'])+' | '+hx(preferred['stored_promoted_double']['native_double_hex'])+' | '+hx(o['physical_getter']['native_double_hex'])+' | '+kind+' '+preferred['case_id']+'/'+preferred['column']+' |')
    lines += ['', '## Candidate meaning / stop conditions', '',
      'The CASE preserves source double operation order: floor of signed input, scaled fractional remainder, nearest-even tie CASE, divide100, add original floor, range clip ±(1e6−1/100), finally REAL. It deliberately uses neither ROUND nor DECIMAL nor ABS. Intermediate X/WHOLE/SCALED/LOWER_I/ROUNDED_I/QUANTIZED/CAP/CLIPPED and HALF_SIDE/WAS_CLIPPED expose arithmetic stages. NULL propagates, with explicit INPUT_IS_NULL. This is a literal observation, not a storage repair.', '',
      'MySQL source pin9bb243a3fa252257468bbcd98f668bfe15bed48c field.cc4028–4062/4290–4334 supports parse64 → quantize/clip → float32, not float32 first. Exact half-tie B observations support nearest-even; actual FENV remains unmeasured. C parser/optimizer/intermediate double behavior is still unproven. If it differs, preserve the difference; do not rewrite SQL or pre-transform the input.', '',
      'Compare native-double HEX including signed zero. Original B MD −0 becomes +0, original B RAW32 −0 and C REAL −0 retain sign; the old derived JSON loses 72 negative-zero displays, with intact original bits. Do not use its numeric fields as new oracle.', '',
      'No business source/schema/helper change follows automatically. A passing stored mapping would still need explicitly scoped Nutrition/Template write-path integration and direct-field read handling, separate from SUM/computed values. A same POWER alias is insufficient provenance. use_weight/plainFLOAT and TemplateExt.use_volume/VARCHAR remain out of scope.', '',
      '## Pure formatter observation (0 SQL)', '',
      'Original raw bits reconstructed on actual B PHP7.3.33 and C PHP7.3.32: `(float)sprintf("%.2F", mappedPhysical32)` matches all288 physical getter oracles (48NULL; 240 nonNULL). Old240 stored inputs have decimal30-roundtrip limitation; half48 are actual computed bits. Explicit context guard leaves all60 computed/aggregate values bit-identical; applying sprintf globally would change36/60. This is finite evidence, not a general helper or implementation authorization.', '',
      'PHP7.3.33 mysqlnd fixed-decimal FLOAT helper formats with snprintf then zend_strtod; snprintf is mapped to ap_php_snprintf. Its finite `%F` path and userland sprintf `%F` call php_conv_fp with explicit dot and precision; source inspection supports the narrow candidate, not universal API semantics. No external source code was executed. See source notes and pure runtime outputs.', '',
      'Only source-model/pure validation has run for this proposal; no new C SELECT, table or DML has run. Root approval of exact proposal SHA required before a runner can connect.', '']
    return '\n'.join(lines)


if __name__ == '__main__':
    print(render(json.loads((R/'proposal.json').read_bytes())), end='')
