import json
import os
import datetime
from song_gen import request_generation
from img_gen import generate_image


def load_sample_data():
    """
    Load all JSON files from the json-files folder into memory.

    Returns:
        list: A list containing the parsed JSON data from all files in the json-files folder
    """
    try:
        # Get the directory of the current file
        current_dir = os.path.dirname(os.path.abspath(__file__))

        # Navigate to the json-files directory (assuming it's in the parent directory)
        json_files_dir = os.path.join(os.path.dirname(current_dir), "json-files")

        all_data = []

        # Check if the directory exists
        if not os.path.isdir(json_files_dir):
            print(f"Error: json-files directory not found at {json_files_dir}")
            return []

        # Iterate through all files in the json-files directory
        for filename in os.listdir(json_files_dir):
            if filename.endswith(".json"):
                file_path = os.path.join(json_files_dir, filename)
                try:
                    # Open and parse each JSON file
                    with open(file_path, "r") as file:
                        file_data = json.load(file)
                        all_data.append(file_data)
                except json.JSONDecodeError:
                    print(f"Error: Invalid JSON format in {filename}")
                except Exception as e:
                    print(f"Error processing {filename}: {str(e)}")

        return all_data
    except Exception as e:
        print(f"Error loading JSON files: {str(e)}")
        return []


def generate_content_for_landing_pages(landing_pages_data):
    """
    Load sample data and generate songs and images for each landing page.

    This function:
    1. Loads the sample data
    2. Iterates through each landing page entry
    3. Generates songs based on song_prompts
    4. Generates images based on image_prompts
    5. Returns a dictionary mapping landing page slugs to their generated content

    Returns:
        dict: A dictionary with landing page slugs as keys and dictionaries of
              generated content (songs and images) as values
    """

    # Dictionary to store generated content for each landing page
    generated_content = {}

    # Process each landing page
    for page_data in landing_pages_data:
        slug = page_data.get("url_slug", "")
        if not slug:
            print(
                f"Warning: Landing page missing URL slug: {page_data.get('title', 'Unknown')}"
            )
            continue

        # Initialize content storage for this landing page
        generated_content[slug] = {"songs": [], "images": []}

        # Generate songs from prompts
        if "song_prompts" in page_data and isinstance(page_data["song_prompts"], list):
            print(f"Generating songs for '{page_data.get('title', slug)}'...")
            for prompt in page_data["song_prompts"]:
                try:
                    song_id = request_generation(prompt)
                    if song_id:
                        generated_content[slug]["songs"].append(
                            {
                                "prompt": prompt,
                                "id": song_id,
                                "song_url": f"https://suno.com/song/{song_id}",
                            }
                        )
                        print(f"  ✓ Generated song: {prompt[:40]}...")
                    else:
                        print(f"  ✗ Failed to generate song: {prompt[:40]}...")
                except Exception as e:
                    print(f"  ✗ Error generating song: {str(e)}")

        # Generate images from prompts
        if "image_prompts" in page_data and isinstance(
            page_data["image_prompts"], list
        ):
            print(f"Generating images for '{page_data.get('title', slug)}'...")
            for prompt in page_data["image_prompts"]:
                try:
                    image_id = generate_image(prompt)
                    if image_id:
                        generated_content[slug]["images"].append(
                            {
                                "prompt": prompt,
                                "id": image_id,
                                "image_url": f"https://cdn1.suno.ai/image_large_{image_id}.jpeg",
                            }
                        )
                        print(f"  ✓ Generated image: {prompt[:40]}...")
                    else:
                        print(f"  ✗ Failed to generate image: {prompt[:40]}...")
                except Exception as e:
                    print(f"  ✗ Error generating image: {str(e)}")

    return generated_content


def generate_mdx_files(generated_content, landing_pages_data):
    """
    Generate MDX files for each landing page based on generated content and original data.

    Args:
        generated_content (dict): Dictionary containing generated songs and images for each landing page
        landing_pages_data (list): Original landing page data with metadata

    Returns:
        list: Paths to the generated MDX files
    """

    print("Generating MDX files for landing pages...")
    mdx_output_dir = "../suno-landing-pages/public/pages"

    # Ensure the output directory exists
    os.makedirs(mdx_output_dir, exist_ok=True)

    generated_files = []

    # Create a lookup dictionary for easier access to original page data
    page_data_lookup = {
        page.get("url_slug", ""): page
        for page in landing_pages_data
        if "url_slug" in page
    }

    for slug, content in generated_content.items():
        mdx_file_path = os.path.join(mdx_output_dir, f"{slug}.mdx")

        try:
            # Get original page data
            original_page_data = page_data_lookup.get(slug, {})

            # Create frontmatter with metadata
            frontmatter = {
                "title": original_page_data.get("title", slug),
                "description": original_page_data.get("description", ""),
                "slug": slug,
                "date": datetime.datetime.now().strftime("%Y-%m-%d"),
            }

            # Format songs section
            songs_section = ""
            if content["songs"]:
                songs_section = "## Generated Songs\n\n"
                for song in content["songs"]:
                    songs_section += f"- [{song['prompt']}]({song['song_url']})\n"

            # Format images section
            images_section = ""
            if content["images"]:
                images_section = "\n\n## Generated Images\n\n"
                for image in content["images"]:
                    images_section += f"![{image['prompt']}]({image['image_url']})\n\n"

            # Add any custom content from the original page data
            custom_content = original_page_data.get("content", "")

            # Get description to use as page copy
            description = frontmatter["description"]

            # Combine all content
            mdx_content = f"""---
title: "{frontmatter["title"]}"
description: "{frontmatter["description"]}"
date: {frontmatter["date"]}
slug: {frontmatter["slug"]}
---

# {frontmatter["title"]}

{description}

{custom_content}

{songs_section}
{images_section}
"""

            # Write the MDX file
            with open(mdx_file_path, "w") as f:
                f.write(mdx_content)

            generated_files.append(mdx_file_path)
            print(f"  ✓ Generated MDX file: {mdx_file_path}")

        except Exception as e:
            print(f"  ✗ Error generating MDX for {slug}: {str(e)}")

    print(f"✓ Generated {len(generated_files)} MDX files")
    return generated_files


if __name__ == "__main__":
    data = load_sample_data()
    # data = data[:1]
    for datum in data:
        generated_content = generate_content_for_landing_pages([datum])
        generated_mdx_files = generate_mdx_files(generated_content, [datum])
    # Write the generated content to a local file
    output_file = "generated_content.json"
    print(f"Writing generated content to {output_file}...")

    try:
        with open(output_file, "w") as f:
            json.dump(generated_content, f, indent=4)
        print(f"✓ Successfully wrote content to {output_file}")
    except Exception as e:
        print(f"✗ Error writing to file: {str(e)}")

    print(generated_content)
