#!/usr/bin/env python3
# json2yaml — convert JSON to YAML using a small built-in emitter (stdlib only, no PyYAML needed).
# Usage: json2yaml input.json [output.yaml]
"""json2yaml: JSON to YAML with zero dependencies. A built-in emitter handles
nested maps/lists, quoted strings when needed, multiline strings as block
scalars, and null/bool/number scalars — the common cases, without PyYAML."""
import argparse, json, sys

def needs_quote(s):
    if s == "" or s != s.strip(): return True
    if s.lower() in ("true", "false", "null", "yes", "no", "on", "off", "~"): return True
    if s[0] in "-?:,[]{}#&*!|>'\"%@`": return True
    if ": " in s or s.endswith(":") or " #" in s: return True
    try:
        float(s); return True
    except ValueError: pass
    return False

def scalar(v):
    if v is None: return "null"
    if v is True: return "true"
    if v is False: return "false"
    if isinstance(v, (int, float)): return repr(v)
    s = str(v)
    if "\n" in s: return None  # block scalar, handled by caller
    return json.dumps(s, ensure_ascii=False) if needs_quote(s) else s

def emit(v, indent, out):
    pad = "  " * indent
    if isinstance(v, dict):
        if not v: out.append(pad + "{}\n"); return
        for k, val in v.items():
            key = json.dumps(str(k), ensure_ascii=False) if needs_quote(str(k)) else str(k)
            if isinstance(val, (dict, list)) and val:
                out.append(f"{pad}{key}:\n"); emit(val, indent + 1, out)
            elif isinstance(val, str) and "\n" in val:
                out.append(f"{pad}{key}: |-\n")
                for line in val.split("\n"): out.append(f"{pad}  {line}\n")
            else:
                out.append(f"{pad}{key}: {scalar(val)}\n")
    elif isinstance(v, list):
        if not v: out.append(pad + "[]\n"); return
        for item in v:
            if isinstance(item, (dict, list)) and item:
                out.append(f"{pad}-\n"); emit(item, indent + 1, out)
            elif isinstance(item, str) and "\n" in item:
                out.append(f"{pad}- |-\n")
                for line in item.split("\n"): out.append(f"{pad}  {line}\n")
            else:
                out.append(f"{pad}- {scalar(item)}\n")
    else:
        out.append(f"{pad}{scalar(v)}\n")

def convert(inp, out):
    with open(inp, encoding="utf-8") as f: data = json.load(f)
    lines = []
    emit(data, 0, lines)
    text = "".join(lines)
    if out:
        open(out, "w", encoding="utf-8").write(text)
    else:
        sys.stdout.write(text)
    return 0

def selftest():
    import tempfile, os
    with tempfile.TemporaryDirectory() as d:
        j = os.path.join(d, "a.json")
        json.dump({"name": "ann", "age": 42, "admin": True, "note": "line1\nline2",
                   "tags": ["a", "b"], "addr": {"city": "Oslo"}, "empty": None,
                   "weird": "yes: maybe"}, open(j, "w"))
        o = os.path.join(d, "a.yaml")
        assert convert(j, o) == 0
        text = open(o).read()
        assert "name: ann" in text and "age: 42" in text and "admin: true" in text
        assert "city: Oslo" in text and "empty: null" in text and "|-\n" in text
        assert '"yes: maybe"' in text or "'yes: maybe'" in text
    print("json2yaml selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="Convert JSON to YAML with a built-in emitter (no PyYAML needed).")
    ap.add_argument("input", nargs="?"); ap.add_argument("output", nargs="?")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    if not a.input: ap.error("need an input JSON file")
    return convert(a.input, a.output)

if __name__ == "__main__":
    sys.exit(main())
