import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "agents"))

from agents.requirement_analyzer import analyze_requirements
from agents.game_designer import design_game
from agents.component_generator import generate_component, save_component
from agents.code_assembler import assemble_game
from agents.streamlit_integrator import save_streamlit_wrapper

def create_game(user_input: str):
    print("Analyzing requirements...")
    requirements = analyze_requirements(user_input)
    
    print("Designing game...")
    design_doc = design_game(requirements)
    print(design_doc)
    
    print("Generating components...")
    components = {
        "player.py": "player",
        "physics.py": "physics",
        "game_objects.py": "objects",
        "level.py": "levels"
    }
    for filename, component in components.items():
        code = generate_component(design_doc, component)
        save_component(code, filename)
    
    print("Assembling game...")
    assemble_game()
    
    print("Creating Streamlit wrapper...")
    save_streamlit_wrapper()
    
    print("Game generation finished.")
    
if __name__ == "__main__":
    import streamlit as st

    st.set_page_config(layout="wide")
    st.title("AI Game Generator")

    if "user_input" not in st.session_state:
        st.session_state.user_input = ""

    st.session_state.user_input = st.text_area("Describe the game you want (e.g. Mario-like platformer):", st.session_state.user_input)

    if st.button("Generate Game"):
        with st.spinner("Generating your game... Please wait a moment."):
            create_game(st.session_state.user_input)
        st.success("Game generated! Use `streamlit run streamlit_app.py` to play.")

    st.info("After generating, run this command in your terminal to launch the game:\n`streamlit run streamlit_app.py`")

this is my main.py file

the below are all the files in agent folder

import os

GENERATED_DIR = os.path.join(os.path.dirname(__file__), "..", "generated_code")
FINAL_GAME_FILE = os.path.join(GENERATED_DIR, "game.py")

def assemble_game():
    # Imports for required files
    imports = [
        "import pygame",
        "from player import Player",
        "from physics import CollisionHandler",
        "from game_objects import Enemy, Coin",
        "from level import Level",
        "import sys"
    ]

    main_code = '''
def run_game():
    pygame.init()
    screen = pygame.display.set_mode((800, 600))
    pygame.display.set_caption("AI Generated Platformer")
    clock = pygame.time.Clock()

    level = Level()
    player = Player()
    collision_handler = CollisionHandler()

    enemies = [Enemy() for _ in range(3)]
    coins = [Coin() for _ in range(5)]

    score = 0
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        
        keys = pygame.key.get_pressed()
        player.handle_input(keys)
        player.update()

        for enemy in enemies:
            enemy.update()
            if collision_handler.check_collision(player, enemy):
                print("Hit enemy! Resetting player.")
                player.reset_position()
        
        for coin in coins[:]:
            if collision_handler.check_collision(player, coin):
                score += 10
                coins.remove(coin)
        
        screen.fill((135, 206, 235))  # sky blue background
        level.draw(screen)
        for platform in level.platforms:
            platform.draw(screen)
        for enemy in enemies:
            enemy.draw(screen)
        for coin in coins:
            coin.draw(screen)
        player.draw(screen)

        # Draw score
        font = pygame.font.Font(None, 36)
        score_text = font.render("Score: " + str(score), True, (0, 0, 0))
        screen.blit(score_text, (10, 10))

        pygame.display.flip()
        clock.tick(60)

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    run_game()
    '''

    content = "\n".join(imports) + "\n" + main_code
    with open(FINAL_GAME_FILE, "w") as f:
        f.write(content)

    print(f"Game assembled at: {FINAL_GAME_FILE}")

if __name__ == "__main__":
    assemble_game()

this is code assembler

from orchestrator import generate_with_gpt
import os

SYSTEM_ROLE_TEMPLATE = (
    "You are a professional Pygame developer. "
    "You will write a complete, self-contained Python module for the {component} "
    "for a platformer game based on the following design:\n\n"
    "{design_doc}\n\n"
    "Requirements:\n"
    "- Respond only with the plain Python code; do NOT include markdown or explanations.\n"
    "- Include all imports required by this module.\n"
    "- Define ALL classes and functions used or referenced by this module.\n"
    "- If the module references classes/functions from another module, provide stub or base implementations here to avoid missing imports.\n"
    "- Implement or include simple asset loading code to load image/sound files from 'assets/' directory with placeholder/fallback assets.\n"
    "- Use clean, modular, readable, and fully commented code.\n"
    "- Ensure functions are called with all required parameters.\n"
    "- Also include code or comments to create the required 'assets/' directory and some minimal placeholder assets (even empty images), or a script to generate them.\n"
)

OUTPUT_DIR = os.path.join(os.path.dirname(__file__), "..", "generated_code")
os.makedirs(OUTPUT_DIR, exist_ok=True)

def generate_component(design_doc: str, component: str) -> str:
    prompt = SYSTEM_ROLE_TEMPLATE.format(component=component, design_doc=design_doc)
    code = generate_with_gpt(prompt, system_role=prompt)
    return code


def save_component(code: str, filename: str):
    path = os.path.join(OUTPUT_DIR, filename)
    with open(path, "w", encoding="utf-8") as f:
        f.write(code)
    print(f"Saved component {filename}")


if __name__ == "__main__":
    design_sample = """
    ## Game Elements
    - Player: Moves with arrow keys, jumps with SPACE
    - Enemies: Patrol platform, reset on collision
    - Coins: Collectible +10 points
    - Platforms: Static collidable surfaces

    ## Game Loop
    1. Render scene
    2. Process input
    3. Update positions
    4. Check collisions
    5. Update score
    """

    components = {
        "player.py": "player",
        "physics.py": "physics",
        "game_objects.py": "objects",
        "level.py": "levels"
    }

    for filename, component in components.items():
        code = generate_component(design_sample, component)
        save_component(code, filename)

this is component genrator

from orchestrator import generate_with_gpt

SYSTEM_ROLE = ("You are a game designer. "
               "Based on the structured requirements JSON, create a detailed game design document "
               "describing game elements, controls, mechanics, and a simplified game loop in markdown.")

def design_game(requirements_json: dict) -> str:
    import json
    prompt = json.dumps(requirements_json, indent=2)

    md_design = generate_with_gpt(prompt, SYSTEM_ROLE)
    return md_design


if __name__ == "__main__":
    sample_reqs = {
        "core_mechanics": ["platforming", "jumping", "collision"],
        "assets": ["player", "enemies", "coins", "platforms"],
        "rules": ["score system", "lives system"],
        "visuals": ["2D side-scroller"]
    }
    print(design_game(sample_reqs))

this is game designer

import os
from openai import AzureOpenAI

def create_client():
    api_key = ""  # set this in your environment
    endpoint = "" # e.g. https://your-resource.openai.azure.com
    if not api_key or not endpoint:
        raise Exception("Set AZURE_OPENAI_API_KEY and AZURE_OPENAI_ENDPOINT environment variables.")
    client = AzureOpenAI(
        api_key=api_key,
        azure_endpoint=endpoint,
        api_version="2024-02-01"
    )
    return client

def generate_with_gpt(prompt: str, system_role: str, temperature: float = 0.3) -> str:
    """
    Generate a completion from Azure OpenAI GPT model.
    """
    client = create_client()
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": system_role},
            {"role": "user", "content": prompt}
        ],
        temperature=temperature
    )
    return response.choices[0].message.content

this is orchestor.py

import re
import json
from orchestrator import generate_with_gpt

SYSTEM_ROLE = (
    "You are a game requirements analyzer. "
    "Given a user request to create a game, extract core mechanics, assets, rules, and visuals as a JSON. "
    "Respond only with a JSON object, no extra explanations or markdown."
)

def extract_json_from_response(response: str) -> str:
    """
    Extract JSON string from LLM response containing markdown code block or plain JSON.
    """
    # Try to extract JSON inside ```json ... ``` block
    pattern = r"```json\s*(\{.*?\})\s*```"
    match = re.search(pattern, response, re.DOTALL)
    if match:
        return match.group(1)

    # If no markdown block, try to find JSON object from first '{' to last '}'
    start = response.find("{")
    end = response.rfind("}")
    if start != -1 and end != -1 and start < end:
        return response[start:end + 1]

    raise ValueError("No JSON content found in the response.")

def analyze_requirements(user_input: str) -> dict:
    response = generate_with_gpt(user_input, SYSTEM_ROLE)
    # Debug print the response to help troubleshoot if needed
    print("GPT Response for Requirements:\n", response)

    json_str = extract_json_from_response(response)

    try:
        requirements = json.loads(json_str)
    except Exception as e:
        raise ValueError(f"Failed to parse requirements JSON: {e}\nResponse was: {response}")

    return requirements

if __name__ == "__main__":
    user_req = "Create a Mario-like platformer game."
    reqs = analyze_requirements(user_req)
    print(json.dumps(reqs, indent=2))

this is requirement analyze

def generate_streamlit_wrapper() -> str:
    code = '''
import streamlit as st
import sys
import os

# Adjust the path to include the generated_code directory
sys.path.append(os.path.join(os.path.dirname(__file__), "generated_code"))

import game  # The assembled game module

st.title("AI-Generated Mario-like Platformer")

if st.button("Start Game"):
    st.write("Launching game window...")
    game.run_game()
    '''

    return code

def save_streamlit_wrapper():
    with open("streamlit_app.py", "w", encoding="utf-8") as f:
        f.write(generate_streamlit_wrapper())
    print("Saved Streamlit wrapper as streamlit_app.py")

if __name__ == "__main__":
    save_streamlit_wrapper()

this is streamlit integrator file

what is happening right now is that the file which are genrated are missing the class which are import in different file also the assets which are need to be there are also not preset, also the parameter are missing when calling any other class or function 

so make it more proper