import os
import io
import re
import streamlit as st
st.set_page_config(layout="wide", initial_sidebar_state="collapsed")
from PIL import Image
import fitz
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
available_fonts = {
    "NotoEmoji Variable": "NotoEmoji-VariableFont_wght.ttf",
    "NotoEmoji Bold": "NotoEmoji-Bold.ttf",
    "NotoEmoji Light": "NotoEmoji-Light.ttf",
    "NotoEmoji Medium": "NotoEmoji-Medium.ttf",
    "NotoEmoji Regular": "NotoEmoji-Regular.ttf",
    "NotoEmoji SemiBold": "NotoEmoji-SemiBold.ttf"
}
with st.sidebar:
    selected_font_name = st.selectbox(
        "Select NotoEmoji Font",
        options=list(available_fonts.keys())
    )
    selected_font_path = available_fonts[selected_font_name]
    
    auto_size = st.checkbox("Auto-size text", value=True)
    base_font_size = st.slider("Base Font Size (points)", min_value=6, max_value=16, value=10, step=1)
    if auto_size:
        st.info("Font size will adjust between 6-16 points based on content length, starting from your base size.")
    
    show_subitems = st.checkbox("Show Sub-items (e.g., 1.1, 2.1.3)", value=True)
    plain_text_mode = st.checkbox("Render as Plain Text (Preserve Bold Only)", value=False)
    
    num_columns = st.radio(
        "Number of Columns",
        options=[1, 2, 3, 4, 5, 6],
        index=3
    )
pdfmetrics.registerFont(TTFont(selected_font_name, selected_font_path))
def apply_emoji_font(text, emoji_font):
    emoji_pattern = re.compile(
        r"([\U0001F300-\U0001F5FF"
        r"\U0001F600-\U0001F64F"
        r"\U0001F680-\U0001F6FF"
        r"\U0001F700-\U0001F77F"
        r"\U0001F780-\U0001F7FF"
        r"\U0001F800-\U0001F8FF"
        r"\U0001F900-\U0001F9FF"
        r"\U0001FA00-\U0001FA6F"
        r"\U0001FA70-\U0001FAFF"
        r"\u2600-\u26FF"
        r"\u2700-\u27BF]+)"
    )
    def replace_emoji(match):
        emoji = match.group(1)
        if len(emoji) > 1:
            emoji = emoji[0]
        return f'{emoji}'
    return emoji_pattern.sub(replace_emoji, text)
default_markdown = """# 🌟 Deities Guide: Mythology and Moral Lessons 🌟
## 1. 📜 Introduction
1. Purpose: Explore deities, spirits, saints, and beings with their stories and morals.  
2. Usage: Guide for learning and storytelling across traditions.  
3. Themes: Justice, faith, hubris, redemption, cosmic order.
## 2. 🛠️ Core Concepts of Divinity
1. Powers: Creation, omniscience, shapeshifting across entities.  
2. Life Cycle: Mortality, immortality, transitions (e.g., saints, avatars).  
3. Communication: Omens, visions, miracles from gods and spirits.
### 2.1. ⚡ Standard Abilities
1. Creation: Gods and spirits shape worlds (e.g., Allah, Vishnu).  
2. Influence: Saints, prophets intercede (e.g., Muhammad, Paul).  
3. Transformation: Angels, avatars shift forms (e.g., Gabriel, Krishna).  
4. Knowledge: Foresight or revelation (e.g., Holy Spirit, Brahma).  
5. Judgment: Divine authority (e.g., Yahweh, Yama).
### 2.2. ⏳ Mortality and Immortality
1. Gods: Eternal (e.g., Allah, Shiva).  
2. Spirits: Realm-bound (e.g., jinn, devas).  
3. Saints/Prophets: Mortal to divine (e.g., Moses, Rama).  
4. Beings: Limbo states (e.g., cherubim, rakshasas).  
5. Lessons: Faith, duty define transitions.
### 2.3. 🌠 Ascension and Signs
1. Paths: Birth, deeds, revelation (e.g., Jesus, Arjuna).  
2. Signs: Miracles, prophecies (e.g., Quran, Gita).  
3. Morals: Obedience, devotion shape destiny.
## 3. 🎲 Storytelling and Games
1. Portrayal: Gods, spirits, saints in narratives or RPGs.  
2. Dynamics: Clerics, imams, sadhus serve higher powers.  
3. Balance: Power vs. personality for depth.
### 3.1. 🎮 Dungeon Mastering Beings
1. Gods: Epic scope (e.g., Allah, Vishnu).  
2. Spirits: Local influence (e.g., jinn, apsaras).  
3. Saints: Moral anchors (e.g., St. Francis, Ali).
### 3.2. 🙏 Devotee Relationships
1. Clerics: Serve gods (e.g., Krishna’s priests).  
2. Mediums: Channel spirits (e.g., jinn whisperers).  
3. Faithful: Venerate saints/prophets (e.g., Fatima’s followers).
## 4. 🌐 Traditions and Legends
*(Top three figures—gods, spirits, saints, beings—with relationships and morals)*  
1. **American Indian** 🦅  
   1. Coyote, Raven, White Buffalo Woman: Trickster kin and wise mother.  
   2. Relation: Siblings and guide teach balance.  
   3. Lesson: Chaos breeds wisdom.  
2. **Arthurian** ⚔️  
   1. Merlin, Morgan le Fay, Arthur: Mentor, rival, son.  
   2. Relation: Family tests loyalty.  
   3. Lesson: Honor vs. betrayal.  
3. **Babylonian** 🏛️  
   1. Marduk, Tiamat, Ishtar: Son, mother, lover.  
   2. Relation: Kinship drives order.  
   3. Lesson: Power reshapes chaos.  
4. **Christian: Trinity** ✝️  
   1. God (Yahweh), Jesus, Holy Spirit: Father, Son, Spirit.  
   2. Relation: Divine family redeems.  
   3. Lesson: Faith restores grace.  
5. **Christian: Saints & Angels** 😇  
   1. St. Michael, Gabriel, Mary: Warrior, messenger, mother.  
   2. Relation: Heavenly kin serve God.  
   3. Lesson: Duty upholds divine will.  
6. **Celtic** 🍀  
   1. Lugh, Morrigan, Cernunnos: Son, mother, father.  
   2. Relation: Family governs cycles.  
   3. Lesson: Courage in fate.  
7. **Central American** 🌄  
   1. Quetzalcoatl, Tezcatlipoca, Huitzilopochtli: Brothers and war son.  
   2. Relation: Sibling rivalry creates.  
   3. Lesson: Sacrifice builds worlds.  
8. **Chinese** 🐉  
   1. Jade Emperor, Nuwa, Sun Wukong: Father, mother, rebel son.  
   2. Relation: Family enforces harmony.  
   3. Lesson: Duty curbs chaos.  
9. **Cthulhu** 🐙  
   1. Cthulhu, Nyarlathotep, Yog-Sothoth: Elder kin.  
   2. Relation: Cosmic trio overwhelms.  
   3. Lesson: Insignificance humbles.  
10. **Egyptian** ☥  
    1. Ra, Osiris, Isis: Father, son, mother.  
    2. Relation: Family ensures renewal.  
    3. Lesson: Justice prevails.  
11. **Finnish** ❄️  
    1. Väinämöinen, Louhi, Ukko: Son, mother, father.  
    2. Relation: Kinship tests wisdom.  
    3. Lesson: Perseverance wins.  
12. **Greek** 🏛️  
    1. Zeus, Hera, Athena: Father, mother, daughter.  
    2. Relation: Family rules with tension.  
    3. Lesson: Hubris meets wisdom.  
13. **Hindu: Trimurti** 🕉️  
    1. Brahma, Vishnu, Shiva: Creator, preserver, destroyer.  
    2. Relation: Divine trio cycles existence.  
    3. Lesson: Balance sustains life.  
14. **Hindu: Avatars & Devis** 🌺  
    1. Krishna, Rama, Durga: Sons and fierce mother.  
    2. Relation: Avatars and goddess protect dharma.  
    3. Lesson: Duty defeats evil.  
15. **Japanese** 🌸  
    1. Amaterasu, Susanoo, Tsukuyomi: Sister, brothers.  
    2. Relation: Siblings balance cosmos.  
    3. Lesson: Harmony vs. chaos.  
16. **Melnibonean** 🗡️  
    1. Arioch, Xiombarg, Elric: Lords and mortal son.  
    2. Relation: Pact binds chaos.  
    3. Lesson: Power corrupts.  
17. **Muslim: Divine & Messengers** ☪️  
    1. Allah, Muhammad, Gabriel: God, prophet, angel.  
    2. Relation: Messenger reveals divine will.  
    3. Lesson: Submission brings peace.  
18. **Muslim: Spirits & Kin** 👻  
    1. Jinn, Iblis, Khidr: Spirits and guide defy or aid.  
    2. Relation: Supernatural kin test faith.  
    3. Lesson: Obedience vs. rebellion.  
19. **Nehwon** 🏰  
    1. Death, Ningauble, Sheelba: Fateful trio.  
    2. Relation: Guides shape destiny.  
    3. Lesson: Cunning defies fate.  
20. **Nonhumans’** 🧝  
    1. Corellon, Moradin, Gruumsh: Elf, dwarf, orc fathers.  
    2. Relation: Rivals define purpose.  
    3. Lesson: Community endures.  
21. **Norse** ᚱ  
    1. Odin, Frigg, Loki: Father, mother, trickster son.  
    2. Relation: Family faces doom.  
    3. Lesson: Sacrifice costs.  
22. **Sumerian** 🗿  
    1. Enki, Inanna, Anu: Son, daughter, father.  
    2. Relation: Kin wield knowledge.  
    3. Lesson: Ambition shapes.
## 5. 📚 Appendices
1. Planes: Realms of gods, spirits, saints (e.g., Paradise, Svarga).  
2. Symbols: Rituals and artifacts of faith.  
3. Charts: Domains and duties for devotees.
### 5.1. 🌌 Planes of Existence
1. Heaven/Paradise: Christian/Muslim abode.  
2. Svarga: Hindu divine realm.  
3. Underworld: Spirits linger (e.g., Sheol, Naraka).
### 5.2. 🕍 Temple Trappings
1. Cross/Crescent: Christian/Muslim faith.  
2. Mandalas: Hindu devotion.  
3. Relics: Saints’ and prophets’ legacy.
### 5.3. 📊 Clerical Chart
1. Gods: Domains (e.g., creation, mercy).  
2. Spirits: Influence (e.g., guidance, mischief).  
3. Saints/Prophets: Virtues (e.g., justice, prophecy).
"""
def markdown_to_pdf_content(markdown_text, show_subitems=True, plain_text_mode=False, font_size=10, num_columns=4):
    lines = markdown_text.strip().split('\n')
    pdf_content = []
    
    if plain_text_mode:
        for line in lines:
            line = line.strip()
            if not line:
                continue
            if line.startswith('# '):
                continue
            bold_pattern = re.compile(r'\*\*(.*?)\*\*')
            line = bold_pattern.sub(r'\1', line)
            pdf_content.append(line)
    else:
        in_list = False
        current_item = None
        sub_items = []
        
        for line in lines:
            line = line.strip()
            if not line:
                continue
                
            if line.startswith('# '):
                continue
            elif line.startswith('## '):
                if current_item and sub_items:
                    pdf_content.append([current_item, sub_items])
                    sub_items = []
                    current_item = None
                section = line.replace('## ', '').strip()
                pdf_content.append(f"{section}")
                in_list = False
            elif line.startswith('### '):
                if current_item and sub_items:
                    pdf_content.append([current_item, sub_items])
                    sub_items = []
                    current_item = None
                if show_subitems:
                    subsection = line.replace('### ', '').strip()
                    pdf_content.append(f"{subsection}")
                in_list = False
            elif re.match(r'^\d+\.', line):
                if current_item and sub_items:
                    pdf_content.append([current_item, sub_items])
                    sub_items = []
                current_item = line.strip()
                in_list = True
            elif re.match(r'^\d+\.\d+\.', line):
                if show_subitems:
                    sub_items.append(line.strip())
            elif line.startswith('*') and not in_list:
                pdf_content.append(line.strip())
            else:
                if in_list:
                    sub_items.append(line.strip())
                else:
                    pdf_content.append(line.strip())
        
        if current_item and sub_items:
            pdf_content.append([current_item, sub_items])
    
    total_lines = sum(1 + len(subs) if isinstance(item, list) else 1 for item in pdf_content)
    total_chars = sum(len(item) if isinstance(item, str) else len(item[0]) + sum(len(sub) for sub in item[1]) for item in pdf_content)
    avg_line_length = total_chars / total_lines if total_lines > 0 else 1
    
    columns = [[] for _ in range(num_columns)]
    lines_per_column = total_lines / num_columns
    current_line_count = 0
    current_column = 0
    
    for item in pdf_content:
        item_lines = 1 + (len(item[1]) if isinstance(item, list) else 0)
        if current_line_count >= lines_per_column and current_column < num_columns - 1:
            current_column += 1
            current_line_count = 0
        columns[current_column].append(item)
        current_line_count += item_lines
    
    return columns, total_lines, num_columns
def create_main_pdf(markdown_text, base_font_size=10, auto_size=False, show_subitems=True, plain_text_mode=False, num_columns=4):
    buffer = io.BytesIO()
    doc = SimpleDocTemplate(
        buffer, 
        pagesize=(A4[1] * 2, A4[0]),
        leftMargin=36,
        rightMargin=36,
        topMargin=36,
        bottomMargin=36
    )
    
    styles = getSampleStyleSheet()
    story = []
    spacer_height = 10
    columns, total_lines, num_columns = markdown_to_pdf_content(markdown_text, show_subitems, plain_text_mode, base_font_size, num_columns)
    
    if auto_size:
        base_font_size = max(6, min(16, base_font_size * 300 / total_lines))
    
    item_font_size = base_font_size
    subitem_font_size = base_font_size * 0.85
    section_font_size = base_font_size * 1.1
    title_font_size = min(20, base_font_size * 1.4)
    
    title_style = ParagraphStyle(
        'Heading1',
        parent=styles['Heading1'],
        fontName="Helvetica-Bold",
        textColor=colors.darkblue,
        alignment=1,
        fontSize=title_font_size,
        leading=title_font_size * 1.2
    )
    
    section_style = ParagraphStyle(
        'SectionStyle',
        parent=styles['Heading2'],
        fontName="Helvetica-Bold",
        textColor=colors.darkblue,
        fontSize=section_font_size,
        leading=section_font_size * 1.2,
        spaceAfter=2
    )
    
    item_style = ParagraphStyle(
        'ItemStyle',
        parent=styles['Normal'],
        fontName="Helvetica",
        fontSize=item_font_size,
        leading=item_font_size * 1.15,
        spaceAfter=1
    )
    
    subitem_style = ParagraphStyle(
        'SubItemStyle',
        parent=styles['Normal'],
        fontName="Helvetica",
        fontSize=subitem_font_size,
        leading=subitem_font_size * 1.15,
        leftIndent=8,
        spaceAfter=1
    )
    
    story.append(Paragraph(apply_emoji_font("Deities Guide: Mythology and Moral Lessons", selected_font_name), title_style))
    story.append(Spacer(1, spacer_height))
    
    column_cells = [[] for _ in range(num_columns)]
    for col_idx, column in enumerate(columns):
        for item in column:
            if plain_text_mode:
                column_cells[col_idx].append(Paragraph(apply_emoji_font(item, selected_font_name), item_style))
            else:
                if isinstance(item, str) and item.startswith(''):
                    text = item.replace('', '').replace('', '')
                    column_cells[col_idx].append(Paragraph(apply_emoji_font(text, selected_font_name), section_style))
                elif isinstance(item, list):
                    main_item, sub_items = item
                    column_cells[col_idx].append(Paragraph(apply_emoji_font(main_item, selected_font_name), item_style))
                    for sub_item in sub_items:
                        column_cells[col_idx].append(Paragraph(apply_emoji_font(sub_item, selected_font_name), subitem_style))
                else:
                    column_cells[col_idx].append(Paragraph(apply_emoji_font(item, selected_font_name), item_style))
    
    max_cells = max(len(cells) for cells in column_cells)
    for cells in column_cells:
        cells.extend([Paragraph("", item_style)] * (max_cells - len(cells)))
    
    col_width = (A4[1] * 2 - 72) / num_columns
    table_data = list(zip(*column_cells))
    table = Table(table_data, colWidths=[col_width] * num_columns, hAlign='CENTER')
    table.setStyle(TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('BACKGROUND', (0, 0), (-1, -1), colors.white),
        ('GRID', (0, 0), (-1, -1), 0, colors.white),
        ('LINEAFTER', (0, 0), (num_columns-1, -1), 0.5, colors.grey),
        ('LEFTPADDING', (0, 0), (-1, -1), 2),
        ('RIGHTPADDING', (0, 0), (-1, -1), 2),
        ('TOPPADDING', (0, 0), (-1, -1), 1),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 1),
    ]))
    
    story.append(table)
    doc.build(story)
    buffer.seek(0)
    return buffer.getvalue()
def pdf_to_image(pdf_bytes):
    try:
        doc = fitz.open(stream=pdf_bytes, filetype="pdf")
        images = []
        for page in doc:
            pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
            img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
            images.append(img)
        doc.close()
        return images
    except Exception as e:
        st.error(f"Failed to render PDF preview: {e}")
        return None
if 'markdown_content' not in st.session_state:
    st.session_state.markdown_content = default_markdown
with st.spinner("Generating PDF..."):
    pdf_bytes = create_main_pdf(st.session_state.markdown_content, base_font_size, auto_size, show_subitems, plain_text_mode, num_columns)
with st.container():
    pdf_images = pdf_to_image(pdf_bytes)
    if pdf_images:
        for i, img in enumerate(pdf_images):
            st.image(img, caption=f"Multi-Column Spread", use_container_width=True)
    else:
        st.info("Download the PDF to view it locally.")
st.download_button(
    label="Download PDF",
    data=pdf_bytes,
    file_name="deities_guide_multi_column.pdf",
    mime="application/pdf"
)
edited_markdown = st.text_area(
    "Modify the markdown content below:",
    value=st.session_state.markdown_content,
    height=300
)
if st.button("Update PDF"):
    st.session_state.markdown_content = edited_markdown
    st.rerun()
st.download_button(
    label="Save Markdown",
    data=st.session_state.markdown_content,
    file_name="deities_guide.md",
    mime="text/markdown"
)