import json
import subprocess
from typing import Any

from .prompts import GEMINI_PROMPTS

class StepRunner:
    def compile_step_prompt(self, step: dict[str, Any]) -> str:
        """Compiles the TURN 3+ prompt for Gemini."""
        return GEMINI_PROMPTS["TURN_3_STEP"].format(
            step_id=step.get("id", "UNKNOWN"),
            task=step.get("task", "No task provided"),
            requirements="\n".join([f"- {req}" for req in step.get("requirements", [])]),
            validation="\n".join([f"- {val}" for val in step.get("validation", [])])
        )

    def run_step(self, step: dict[str, Any]) -> dict[str, Any]:
        prompt = self.compile_step_prompt(step)
        
        result: dict[str, Any] = {
            "step_id": step["id"],
            "files_created": [],
            "commands_run": [],
            "validation_passed": False,
            "errors": []
        }

        try:
            for cmd in step.get("commands", []):
                result["commands_run"].append(cmd)
                cp = subprocess.run(cmd, shell=True, capture_output=True, text=True)
                if cp.returncode != 0:
                    result["errors"].append(
                        f"Command failed ({cp.returncode}): {cmd}\n"
                        f"STDOUT: {cp.stdout}\n"
                        f"STDERR: {cp.stderr}"
                    )
                    return result

            result["files_created"] = step.get("expected_files", [])

            val_passed = True
            for val_cmd in step.get("validation", []):
                v_cp = subprocess.run(val_cmd, shell=True, capture_output=True, text=True)
                if v_cp.returncode != 0:
                    val_passed = False
                    result["errors"].append(
                        f"Validation failed ({v_cp.returncode}): {val_cmd}\n"
                        f"STDOUT: {v_cp.stdout}\n"
                        f"STDERR: {v_cp.stderr}"
                    )
                    break
            result["validation_passed"] = val_passed

        except Exception as e:
            result["errors"].append(str(e))

        return result
