#!/usr/bin/env python3

import argparse
from pathlib import Path
import subprocess
import sys
import os
import io

from registry import registry


def main() -> None:
    parser = argparse.ArgumentParser(description="Submit changes for review")
    parser.add_argument("-f", "--force", action="store_true", help="Force submit without review")
    args = parser.parse_args()

    repo_root = registry.get("ROOT", os.getenv("ROOT"))
    assert repo_root

    patch_path = Path("/root/model.patch")

    subprocess.run(
        f"git add -A && git diff --cached > {patch_path}",
        shell=True,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
        cwd=repo_root,
    )

    patch = patch_path.read_text(encoding="utf-8", errors="backslashreplace")

    if not args.force and not registry.get("SUBMIT_TRIGGERED_BEFORE"):
        message = registry.get("SUBMIT_REVIEW_MESSAGE", "")
        message = message.replace("{{diff}}", patch)
        message = message.replace("{{problem_statement}}", registry.get("PROBLEM_STATEMENT", ""))
        registry["SUBMIT_TRIGGERED_BEFORE"] = True
        # work around any encoding issues
        message = message.encode("utf-8", errors="backslashreplace").decode("utf-8")
        print(message)
        sys.exit(0)

    print("<<SWE_AGENT_SUBMISSION>>")
    print(patch)
    print("<<SWE_AGENT_SUBMISSION>>")


if __name__ == "__main__":
    # There are some super strange "ascii can't decode x" errors when printing to the terminal
    # that can be solved with setting the default encoding for stdout
    # (note that python3.6 doesn't have the reconfigure method)
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
    main()
