"""Patches node-agent to store bridge per-port format JSON and inject into sidecar env."""
with open('services/node-agent/index.js') as f:
    s = f.read()

# 1. Add per-port format cache
old1 = "const _containerSourceType = new Map();"
new1 = ("const _containerSourceType = new Map();\n"
        "// port -> fmt JSON from bridge stderr (inject into sidecar env)\n"
        "const _dcPortFmt = new Map();")
assert old1 in s, "MISS: _containerSourceType"
s = s.replace(old1, new1, 1)

# 2. Parse format JSON in bridge stderr handler
old2 = ("      if (t.startsWith('{')) console.log('[dc-bridge] ' + t);\n"
        "      else                   console.error('[dc-bridge] ' + t);")
new2 = ("      if (t.startsWith('{')) {\n"
        "        console.log('[dc-bridge] ' + t);\n"
        "        try { const f = JSON.parse(t); if (typeof f.port === 'number') _dcPortFmt.set(f.port, f); } catch (_) {}\n"
        "      } else {\n"
        "        console.error('[dc-bridge] ' + t);\n"
        "      }")
assert old2 in s, "MISS: stderr handler"
s = s.replace(old2, new2, 1)

# 3. Inject env after startDeltacastBridge()
old3 = ("    if (sourceType === 'deltacast') {\n"
        "      _dcSidecarCount++;\n"
        "      startDeltacastBridge();")
new3 = ("    if (sourceType === 'deltacast') {\n"
        "      _dcSidecarCount++;\n"
        "      startDeltacastBridge();\n"
        "      // Inject per-port signal format so capture-manager uses real dimensions/fps\n"
        "      const _srcCfg = (env.find(e => e.startsWith('SOURCE_CONFIG=')) || '').slice(14);\n"
        "      let _portNum = NaN;\n"
        "      try { _portNum = JSON.parse(_srcCfg).port; } catch (_) {}\n"
        "      if (Number.isFinite(_portNum) && _dcPortFmt.has(_portNum)) {\n"
        "        const _fmt = _dcPortFmt.get(_portNum);\n"
        "        const _fps = (_fmt.fps_den && _fmt.fps_den !== 1) ? `${_fmt.fps_num}/${_fmt.fps_den}` : String(_fmt.fps_num);\n"
        "        sidecarEnv.push(`DELTACAST_VIDEO_SIZE=${_fmt.width}x${_fmt.height}`);\n"
        "        sidecarEnv.push(`DELTACAST_FRAMERATE=${_fps}`);\n"
        "        sidecarEnv.push(`DELTACAST_INTERLACED=${_fmt.interlaced ? '1' : '0'}`);\n"
        "        console.log(`[dc-bridge] port ${_portNum} fmt: ${_fmt.width}x${_fmt.height} ${_fps} interlaced=${_fmt.interlaced}`);\n"
        "      }")
assert old3 in s, "MISS: sidecar start deltacast block"
s = s.replace(old3, new3, 1)

with open('services/node-agent/index.js', 'w') as f:
    f.write(s)
print("PATCHED OK")
