#!/usr/bin/env python3
"""Produce a renamed-tags variant of the rendered Form-A spec.

Two modes:
- apply: full-form resolution of abbreviations
    app→apply, lam→lambda, ctor→constructor, con→typecon, tail-app→tail-apply
- call: like apply but with call as the application head (semantic shift)
    app→call, tail-app→tail-call, rest as in apply

Each pattern is matched in two contexts:
- S-expression head:  `(NAME ` and `(NAME)`
- Backtick mention:   `` `NAME` ``

Plain-text occurrences ("application", "construction", etc.) are
preserved by anchoring on the contexts above.
"""
import re
import sys
from pathlib import Path

PAIRS_APPLY = [
    ("tail-app",  "tail-apply"),
    ("term-ctor", "term-constructor"),
    ("pat-ctor",  "pat-constructor"),
    ("ctor",      "constructor"),
    ("app",       "apply"),
    ("lam",       "lambda"),
    ("con",       "typecon"),
]

PAIRS_CALL = [
    ("tail-app",  "tail-call"),
    ("term-ctor", "term-constructor"),
    ("pat-ctor",  "pat-constructor"),
    ("ctor",      "constructor"),
    ("app",       "call"),
    ("lam",       "lambda"),
    ("con",       "typecon"),
]

MODES = {"apply": PAIRS_APPLY, "call": PAIRS_CALL}

def transform(src: str, pairs) -> str:
    out = src
    for old, new in pairs:
        out = re.sub(rf"\({re.escape(old)}(?=[\s)])", f"({new}", out)
        out = re.sub(rf"`{re.escape(old)}`", f"`{new}`", out)
    return out

def main() -> int:
    if len(sys.argv) != 4 or sys.argv[1] not in MODES:
        print(f"usage: {sys.argv[0]} <apply|call> <input.md> <output.md>", file=sys.stderr)
        return 2
    mode = sys.argv[1]
    inp = Path(sys.argv[2])
    out = Path(sys.argv[3])
    out.write_text(transform(inp.read_text(), MODES[mode]))
    print(f"wrote {out} ({out.stat().st_size} bytes, mode={mode})")
    return 0

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