#!/usr/bin/env python3
import sys
import xml.etree.ElementTree as ET
import subprocess
from pathlib import Path

def compile_cux_to_c(input_path, c_path):
    tree = ET.parse(input_path)
    root = tree.getroot()

    program = root.find("program")
    if program is None:
        print("Error: <program> block not found in CedarUX file")
        sys.exit(1)

    lines = []
    lines.append('#include <stdio.h>')
    lines.append('int main() {')

    for node in program:
        if node.tag == "print":
            text = (node.text or "").replace('"', '\\"')
            lines.append(f'    printf("{text}\\n");')

    lines.append('    return 0;')
    lines.append('}')

    c_path.write_text("\n".join(lines), encoding="utf-8")

def main():
    if len(sys.argv) != 3:
        print("Usage: cucc <input.cux> <output_binary>")
        sys.exit(1)

    input_path = Path(sys.argv[1])
    output_path = Path(sys.argv[2])
    c_path = output_path.with_suffix(".c")

    compile_cux_to_c(input_path, c_path)

    # Call gcc to build the binary
    subprocess.check_call(["gcc", str(c_path), "-o", str(output_path)])

    print(f"Compiled {input_path} -> {output_path}")

if __name__ == "__main__":
    main()
