#!/usr/bin/env python3

import os
import sys
from pathlib import Path


error_report_path = Path("error_reports")
error_report_path.mkdir(exist_ok=True, parents=True)


def process_queue(filename="queue.md"):
    try:
        with open(filename, "r") as f:
            content = f.read()
    except FileNotFoundError:
        print(f"Error: {filename} not found")
        sys.exit(1)

    paragraphs = content.split("\n\n")

    commands = []
    for paragraph in paragraphs:
        commands.append(paragraph.replace("\n", " ").replace("'", '"').strip())
        # commands.append(
        #     "Run all unit-tests and fix them if they are broken. Re-run and fix until all unit-tests are green"
        # )

    commands = [c.strip() for c in commands if c.strip()]

    for i, command in enumerate(commands):
        number_of_error_reports_before = len(
            list(error_report_path.glob("*.md")))

        # command += "    After you did your job, reflect if you achieved the goals. If not, write up your problems into a new markdown-file in ./error_reports. This should only happen on the most critical"

        should_flush = (i % 3 == 0)

        continue_flag = "-c"
        if should_flush:
            continue_flag = ""

        if not command.strip():
            continue

        shell_command = (
            f"claude {
                continue_flag} -p --dangerously-skip-permissions '{command}'"
        )
        exit_code = os.system(shell_command)

        print(shell_command)
        if exit_code != 0:
            print(f"\nWarning: Command exited with code {exit_code}")
            break

        number_of_error_reports_after = len(
            list(error_report_path.glob("*.md")))

        if False and number_of_error_reports_after > number_of_error_reports_before:
            print(
                f"\nError report created: {
                    number_of_error_reports_after - number_of_error_reports_before
                } new error reports found."
            )
            break


if __name__ == "__main__":
    process_queue()
