from datetime import date, datetime
import os
from music_generator import generate_music_site # Import the new function
from annotation_generator import generate_annotation_site # Import the annotation generator
import sys # For printing errors
import shutil # For copying folders
import logging # Import logging
import markdown # For parsing markdown

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_OUTPUT_DIR = os.path.join(CURRENT_DIR, "output")
MUSIC_OUTPUT_DIR = os.path.join(BASE_OUTPUT_DIR, "music")
ANNOTATION_OUTPUT_DIR = os.path.join(BASE_OUTPUT_DIR, "annotations") # Define annotation output dir
MAIN_INDEX_MD_PATH = os.path.join(CURRENT_DIR, "md/index.md")

# Define where templates and the music index markdown file are located
# (Relative to this generator.py script)
TEMPLATES_DIR = os.path.join(CURRENT_DIR) # Root directory contains templates folder
# Folders containing shared assets to copy to the base output directory
FOLDERS_TO_COPY = ["assets", "styles", "scripts"] 

def generate_main_index_page(output_dir, templates_dir):
    """Generates the main index.html page for the site using the generic list template."""
    from jinja2 import Environment, FileSystemLoader

    logging.info("Generating main index page...")

    # Set up Jinja2 environment
    jinja_env = Environment(loader=FileSystemLoader(templates_dir))

    # Read the index.md content for the left pane
    site_description_html = "<p>Main site content not available.</p>"
    if os.path.exists(MAIN_INDEX_MD_PATH):
        try:
            with open(MAIN_INDEX_MD_PATH, "r", encoding="utf-8") as f:
                index_md_content = f.read()
            md_parser = markdown.Markdown()
            site_description_html = md_parser.convert(index_md_content)
            logging.info(f"Successfully read and converted {MAIN_INDEX_MD_PATH}")
        except Exception as e:
            logging.error(f"Error processing {MAIN_INDEX_MD_PATH}: {e}")
    else:
        logging.warning(f"{MAIN_INDEX_MD_PATH} not found. Using default description.")

    # Define available sections data
    sections_data = [
        {
            "name": "Music",
            "url": "/music/", # Ensure trailing slash for consistency
            "description": "Browse my favorite music albums and reviews."
        },
        {
            "name": "Web",
            "url": "/annotations/", # Ensure trailing slash
            "description": "Explore various annotations on the web."
        },
        {
            "name": "Thoughts",
            "url": "/thoughts/", # Ensure trailing slash
            "description": "Read my thoughts on various topics."
        },
        {
            "name": "Clicks",
            "url": "/clicks/", # Ensure trailing slash
            "description": "Explore my various clicks."
        },
        {
            "name": "Books",
            "url": "/books/", # Ensure trailing slash
            "description": "Explore my favorite books."
        },
        {
            "name": "Art",
            "url": "/art/", # Ensure trailing slash
            "description": "Explore my various art projects.Explore my various art projects.Explore my various art projects.Explore my various art projects.Explore my various art projects.Explore my various art projects.Explore my various art projects.Explore my various art projects."
        }
    ]

    # Generate the HTML using the templates
    try:
        # Load the main generic list page template
        template = jinja_env.get_template('templates/list_page_template.html')
        # Load the template for individual section list items
        item_template = jinja_env.get_template('templates/list_templates/section_item.html')

        # Render each section item individually
        list_items_html = []
        for section_info in sections_data:
            list_items_html.append(item_template.render(section=section_info))

        # Render the main index page template
        html_content = template.render(
            page_title="WU - Home", # Set the title for the home page
            site_description_html=site_description_html,
            list_items_html=list_items_html, # Pass the list of rendered HTML strings
            show_back_link=False, # Main index does not need the back link
            background_image_url='/assets/bg.png' # Pass the background image URL
        )

        # Write the output file
        output_path = os.path.join(output_dir, "index.html")
        with open(output_path, "w", encoding="utf-8") as f:
            f.write(html_content)
        logging.info(f"Successfully generated main index.html -> {output_path}")
    except Exception as e:
        logging.error(f"Error generating main index.html: {e}")

# --- Main Execution ---
if __name__ == "__main__":

    # --- Configure Logging --- 
    log_format = '%(asctime)s - %(name)s - %(levelname)s: %(message)s'
    logging.basicConfig(level=logging.INFO, format=log_format, stream=sys.stdout) 
    logging.getLogger().setLevel(logging.INFO) 

    # Ensure base output directory exists
    os.makedirs(BASE_OUTPUT_DIR, exist_ok=True)

    # --- Generate Main Index Page ---
    logging.info("--- Generating Main Index Page ---")
    generate_main_index_page(BASE_OUTPUT_DIR, TEMPLATES_DIR)

    # --- Generate Music Section ---
    # logging.info("--- Generating Music Section --- ")
    # Call the dedicated function from the music_generator module
    generate_music_site(
        output_dir=MUSIC_OUTPUT_DIR, 
        templates_dir=TEMPLATES_DIR,
    )
    
    # --- Generate Annotations Section ---
    logging.info("--- Generating Annotations Section --- ")
    generate_annotation_site(
        output_dir=ANNOTATION_OUTPUT_DIR,
        templates_dir=TEMPLATES_DIR # Pass the templates directory
        # templates_dir is handled within annotation_generator
    )
    
    # --- (Add calls to other potential generators here) --- 
    # e.g., generate_blog_section(...)
    
    # --- Copy Shared Assets --- 
    logging.info(f"--- Copying Shared Assets to {BASE_OUTPUT_DIR} ---")
    # Ensure source asset folders exist relative to the *generator* script
    # Copy them to the *base* output directory
    for folder in FOLDERS_TO_COPY:
        src_path = os.path.join(CURRENT_DIR, folder) # Source relative to generator.py
        dst_path = os.path.join(BASE_OUTPUT_DIR, folder) # Destination in the root output

        if not os.path.exists(src_path):
            logging.warning(f"Source folder not found, cannot copy: {src_path}")
            continue

        # Remove existing destination to ensure a clean copy
        if os.path.exists(dst_path):
            logging.debug(f"Removing existing destination folder: {dst_path}")
            shutil.rmtree(dst_path)
        
        logging.debug(f"Copying {src_path} to {dst_path}")
        try:
            shutil.copytree(src_path, dst_path)
        except Exception as e:
            logging.error(f"Error copying folder {src_path} to {dst_path}: {e}")
            
    logging.info("Site generation process finished.")
