from diffusers import DiffusionPipeline
import os
import requests

def generate_design_image(prompt):
    """
    Generate a design image using Hugging Face Diffusers' Stable Diffusion pipeline.
    """
    try:
        # Load Stable Diffusion pipeline
        pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2")
        pipe.to("cpu")  # Ensure CPU usage for compatibility with Hugging Face free-tier

        # Generate the image
        image = pipe(prompt).images[0]

        # Save the image locally (optional)
        output_path = "generated_image.png"
        image.save(output_path)

        # Return the local image path for display
        return output_path

    except Exception as e:
        return f"Error: Failed to generate design image. {str(e)}"

import requests
import os

def create_figma_template(task_description):
    """
    Create a design template using Figma API.
    """
    # Get the Figma API key from environment variables
    FIGMA_API_KEY = os.getenv("FIGMA_API_KEY")
    if not FIGMA_API_KEY:
        return "Error: Missing FIGMA_API_KEY in environment variables."

    # Specify the Figma file key (replace with a valid file key from your Figma account)
    file_key = "figd_MmKjOOzY45ubfU2sIR9ZTCv5SM8mbDq1aN9x2F9h"  # Replace this with your actual Figma file key
    url = f"https://api.figma.com/v1/files/{file_key}"  # Endpoint requires a file key
    headers = {"Authorization": f"Bearer {FIGMA_API_KEY}"}

    try:
        # Make the API call
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # Raise an error for HTTP status codes 4xx/5xx
        
        # Parse the response
        data = response.json()
        if "document" in data:
            # Return the Figma file's public link
            return f"https://www.figma.com/file/{file_key}"
        else:
            return f"Error: No valid response received. Response: {data}"

    except requests.exceptions.RequestException as e:
        return f"Error: Failed to connect to Figma API. {str(e)}"
    except Exception as e:
        return f"Error: An unexpected error occurred. {str(e)}"