import os
import requests
from urllib.parse import quote
import tkinter as tk
from PIL import Image, ImageTk

def UpgradePrompt(prompt: str) -> str:
    return prompt

def generate_and_save_image(prompt: str, path: str, width: int = 3840, height: int = 2160):
    prompt = UpgradePrompt(prompt)
    print(f"Generating image with prompt: {prompt}")
    base_url = "https://image.pollinations.ai/prompt/"
    encoded_prompt = quote(prompt)
    url = f"{base_url}{encoded_prompt}?width={width}&height={height}&nologo=true"
    response = requests.get(url)
    if response.status_code == 200:
        with open(path, "wb") as f:
            f.write(response.content)
        print(f"Image saved to {path}")
    else:
        print(f"Failed to generate image. Status code: {response.status_code}")
        print(response.text)

PREMADE_DESCRIPTIONS = {
    "ForestArena": (
        "ForestArena is a jungle-like battlefield filled with towering trees, "
        "dense undergrowth, and a faint mist. It feels alive and full of secrets."
    ),
    "DesertWasteland": (
        "DesertWasteland is a harsh, sun-scorched expanse with rolling dunes, "
        "dry cracked earth, and relentless heatwaves."
    ),
    "CastleCourtyard": (
        "CastleCourtyard is a grand stone plaza surrounded by tall walls, "
        "banners fluttering in the wind, and the distant sounds of clashing swords."
    ),
}

SKYBOX_DESCRIPTIONS = {
    "SkyNight": "A star-studded night sky with a bright crescent moon casting a cool glow.",
    "SkyDay": "A clear blue sky with soft, fluffy clouds drifting lazily.",
    "SkyStorm": "A dark stormy sky filled with lightning flashes and heavy thunderclouds.",
}

PLAYER_DESCRIPTIONS = {
    "Knight": (
        "A valiant knight clad in shining armor, wielding a broad sword and shield, "
        "ready to defend honor on the battlefield."
    ),
    "Archer": (
        "A swift archer with keen eyes, carrying a finely crafted bow and a quiver full of arrows."
    ),
    "Mage": (
        "A mysterious mage robed in deep blue, holding a staff glowing with arcane energy."
    ),
}

LIGHT_DESCRIPTIONS = {
    "Directional": "Cinematic sunlight.",
    "Point": "Theatrical lighting.",
    "Spot": "A focused lighting illuminating a specific area.",
}

class Game:
    def __init__(self, name):
        self.name = name
        self.current_scene = None
        print(f"[Game] Created game '{name}'")

    def load_scene(self, scene):
        self.current_scene = scene
        print(f"[Game] Scene '{scene.name}' loaded into game '{self.name}'")

    def run(self):
        if not self.current_scene:
            print("[Game] No scene loaded, cannot run game.")
            return
        print(f"[Game] Running game '{self.name}' with scene '{self.current_scene.name}'\n")
        description = self.current_scene.describe()
        print(description)
        img_path = f"{self.current_scene.name}_scene.png"
        generate_and_save_image(description, img_path, width=3840, height=2160)
        self.show_image_window(img_path)

    def show_image_window(self, image_path):
     if not os.path.exists(image_path):
        print(f"Image file {image_path} does not exist. Cannot open window.")
        return
     root = tk.Tk()
     root.title(self.name)
     img = Image.open(image_path)
     screen_w = root.winfo_screenwidth()
     screen_h = root.winfo_screenheight()
     img.thumbnail((screen_w, screen_h), Image.Resampling.LANCZOS)
     img_tk = ImageTk.PhotoImage(img)
     label = tk.Label(root, image=img_tk)
     label.pack()
     label.image = img_tk
     root.mainloop()


class Scene:
    def __init__(self, name, custom=False, description=None):
        self.name = name
        if custom:
            if not description:
                raise ValueError("Custom scene requires a description.")
            self.description = description
        else:
            self.description = PREMADE_DESCRIPTIONS.get(
                name,
                f"{name} is a mysterious place full of adventures."
            )
        self.entities = []
        print(f"[Scene] Scene '{name}' created")

    def add(self, entity):
        self.entities.append(entity)
        print(f"[Scene] Added {entity.describe()} to scene '{self.name}'")

    def describe(self):
        desc = f"Scene '{self.name}': {self.description}\nEntities in the scene:\n"
        for entity in self.entities:
            desc += f"  - {entity.describe()}\n"
        return desc.strip()

    def __str__(self):
        return self.describe()

class Skybox:
    def __init__(self, model):
        self.model = model
        self.description = SKYBOX_DESCRIPTIONS.get(
            model,
            f"A skybox showing the scene '{model}'."
        )

    def describe(self):
        return f"Skybox: {self.description}"

class Light:
    def __init__(self, type="Directional", intensity=1.0, shadows=False):
        self.type = type
        self.intensity = intensity
        self.shadows = shadows
        self.description = LIGHT_DESCRIPTIONS.get(
            type,
            f"A light of type '{type}' with intensity {intensity}."
        )

    def describe(self):
        shadows_text = "with shadows enabled" if self.shadows else "without shadows"
        return f"Light: {self.description}, intensity {self.intensity}, {shadows_text}"

class Player:
    def __init__(self, name, model=None, spawn=(0, 0, 0)):
        self.name = name
        self.model = model
        self.spawn = spawn
        self.description = PLAYER_DESCRIPTIONS.get(
            model,
            f"A player named '{name}' with model '{model}'."
        )

    def describe(self):
        return (f"Player '{self.name}': {self.description} "
                f"Spawned at position {self.spawn}")
