"""Reads a JSON value from stdin (the kind MCP returns when wrapping data),
and writes the decoded value as UTF-8 to the given file.

If the JSON decodes to a plain string it is written verbatim; otherwise
(list/dict/number/etc.) it is re-serialised with json.dumps so f.write
always receives a str."""
import json, sys, os
out_path = sys.argv[1]
raw = sys.stdin.read()
# raw is JSON like "[{\"name\":\"...\"}]" or a JSON-quoted string — already JSON-encoded
decoded = json.loads(raw)
text = decoded if isinstance(decoded, str) else json.dumps(decoded, ensure_ascii=False)
os.makedirs(os.path.dirname(out_path) or '.', exist_ok=True)
with open(out_path, 'w', encoding='utf-8') as f:
    f.write(text)
print(f'wrote {out_path} ({len(text)} chars)')
