#!/usr/bin/env python3
from __future__ import annotations

import argparse
from pathlib import Path
import sys


def save_c_code(c_code: str, output_dir: Path, filename: str = "output.c") -> Path:
    """
    Save a C source code string to a .c file in the given directory.
    """
    output_dir = output_dir.expanduser().resolve()
    output_dir.mkdir(parents=True, exist_ok=True)

    path = output_dir / filename

    # Normalize newlines and ensure trailing newline
    content = c_code.replace("\r\n", "\n").replace("\r", "\n")
    if not content.endswith("\n"):
        content += "\n"

    path.write_text(content, encoding="utf-8")
    return path


def main():
    parser = argparse.ArgumentParser(description="Save C code string to a .c file")
    parser.add_argument(
        "--input",
        required=True,
        help="C source code as a string (quote it in shell)",
    )
    parser.add_argument(
        "--output",
        default=".",
        help="Output directory (default: current directory)",
    )
    parser.add_argument(
        "--filename",
        default="output.c",
        help="Output C file name (default: output.c)",
    )

    args = parser.parse_args()

    output_dir = Path(args.output)

    try:
        saved_path = save_c_code(
            c_code=args.input,
            output_dir=output_dir,
            filename=args.filename,
        )
    except Exception as e:
        print(f"[ERROR] {e}", file=sys.stderr)
        sys.exit(1)

    print(f"[OK] C source saved to: {saved_path}")


if __name__ == "__main__":
    main()



# python3 ./save_c.py --input '
# #include <stdio.h>

# int main() {
#     puts("Generated by agent");
#     return 0;
# }
# ' --output ./ --filename source.c

