import os
from openai import OpenAI
import markdown2
from weasyprint import HTML
from pygments.formatters import HtmlFormatter
from dotenv import load_dotenv
load_dotenv()

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
OUTPUT_FOLDER = os.getenv("OUTPUT_FOLDER", "./result")
working_dir = "imscc_temp"
content_dir = "wiki_content"

def generate_subtopics(topic):
    prompt = f"List 5-7 key subtopics of '{topic}' for beginner students."
    response = client.chat.completions.create(
        model=OPENAI_MODEL,
        messages=[{"role": "user", "content": prompt}]
    )
    response = clientCall(prompt)
    return [line.strip("- ") for line in response.split("\n") if line.strip()]

# Generate Course Objectives
def generate_course_objectives(topic):
    prompt = f"""Generate 4-5 clear **Course Objectives** for a course on the topic: "{topic}". 
Use bullet points and write them from an instructor's perspective, focusing on what the course will deliver."""
    return clientCall(prompt)

# Generate the Course Outcomes
def generate_course_outcomes(topic):
    prompt = f"""Generate 4-5 measurable **Course Outcomes** for a course on "{topic}".
Each outcome should start with a verb (e.g., analyze, explain, apply) and describe what the student will be able to do after completing the course."""
    return clientCall(prompt)

# Generate a high-level Course Outline
def generate_course_outline(topic):
    prompt = f"Generate a high-level numbered Course Outline with 5-10 modules for the topic '{topic}', including module titles and short descriptions."
    return clientCall(prompt)

# Establish the Course Outline
def establish_course_outline(topic):
    prompt = f"""Generate a high-level **Course Outline** for the topic "{topic}".
Include 5-10 modules or units with titles and brief descriptions. Use a structured, numbered list."""
    return clientCall(prompt)

# Generation of Course Module Content (Detailed Outline)
def generate_detailed_course_outline(topic, modules):
    outline = ""
    for module in modules:
        prompt = f"""Expand the module "{module}" from the course on "{topic}" into a detailed outline.
Include learning goals, key concepts, example activities or readings."""
        
        response = clientCall(prompt)
        outline += f"### {module}\n{response}\n\n"
    return outline


def explain_concepts(topic, subtopics):
    explanations = {}
    for sub in subtopics:
        prompt = f"Explain the subtopic '{sub}' under the topic '{topic}' for students using Markdown format. Include examples and clear explanation."
        explanations[sub] = clientCall(prompt)
        
    return explanations

def generate_questions(subtopics):
    questions = {}
    for sub in subtopics:
        prompt = f"Create 3 multiple-choice questions in Markdown for the subtopic '{sub}' with correct answers indicated."
        questions[sub] = clientCall(prompt)
        
    return questions

def generate_summary(topic):
    prompt = f"Give a clear, concise Markdown summary of '{topic}' for student revision."
    return clientCall(prompt)

def clientCall(prompt):
    response = client.chat.completions.create(
        model=OPENAI_MODEL,
        messages=[{"role": "user", "content": prompt}]
    )
    return response.choices[0].message.content.strip()

def extract_module_titles(course_outline):
    lines = course_outline.strip().split("\n")
    titles = []
    for line in lines:
        if ". " in line:
            parts = line.split(". ", 1)
            if len(parts) > 1:
                titles.append(parts[1].split(":")[0].strip())
    return titles

def build_markdown(topic):
    subtopics = generate_subtopics(topic)
    print(f'## Course subtopics generated')
    explanations = explain_concepts(topic, subtopics)
    print(f'## Course explanations generated')
    questions = generate_questions(subtopics)
    print(f'## Course questions generated')
    md = f"# Course: {topic}\n\n"
    # Summary
    summary = generate_summary(topic)
    md += f"## Summary\n{summary}\n\n"
    print(f'## Course Summary generated')

    # Objectives
    objectives = generate_course_objectives(topic)
    md += f"## Course Objectives\n{objectives}\n\n"
    print(f'## Course Objectives generated')
    # Outcomes
    outcomes = generate_course_outcomes(topic)
    md += f"## Course Outcomes\n{outcomes}\n\n"
    print(f'## Course Outcomes generated')
    # Outline
    outline = generate_course_outline(topic)
    md += f"## Course Outline\n{outline}\n\n"
    print(f'## Course Outline generated')
    # Detailed Modules
    module_titles = extract_module_titles(outline)
    detailed_modules = generate_detailed_course_outline(topic, module_titles)
    md += f"## Module Details\n{detailed_modules}"
    print(f'## Course Module Details generated')
    
    for sub in subtopics:
        md += f"## {sub}\n\n"
        md += f"{explanations[sub]}\n\n"
        md += f"### Quiz Questions\n{questions[sub]}\n\n"

    return md

def export_to_html_and_pdf(markdown_content, output_base):
    # Convert markdown to HTML with fenced code and syntax highlight
    extras = ["fenced-code-blocks", "code-friendly", "tables"]
    html_content = markdown2.markdown(markdown_content, extras=extras)
    
    # Add Pygments CSS for code styling
    style = HtmlFormatter().get_style_defs('.codehilite')
    style += """
    body, h1, h2, h3, h4, h5, h6, pre, code {
        word-wrap: break-word;
        overflow-wrap: break-word;
        white-space: normal;
    }
    pre, code {
        white-space: pre-wrap;
    }
    """
    full_html = f"<style>{style}</style>\n{html_content}"

    if not os.path.exists(OUTPUT_FOLDER):
        os.makedirs(OUTPUT_FOLDER, exist_ok=True)

    output_base = os.path.join(OUTPUT_FOLDER, output_base)

    # Save HTML
    html_file = f"{output_base}.html"
    with open(html_file, "w", encoding="utf-8") as f:
        f.write(full_html)

    # Save PDF
    pdf_file = f"{output_base}.pdf"
    HTML(string=full_html).write_pdf(pdf_file)

    print(f"✅ Exported to {html_file} and {pdf_file}")

# -------- Run it --------
if __name__ == "__main__":
    topic = input("Enter an educational topic: ")
    markdown_content = build_markdown(topic)
    base_filename = topic.replace(" ", "_")
    
    # Save markdown
    with open(f"{base_filename}.md", "w", encoding="utf-8") as f:
        f.write(markdown_content)
    
    # base_filename = "Python_Programming_for_beginners"
    # with open(f"{base_filename}.md", "r", encoding="utf-8") as file:
    #     markdown_content = file.read()
    # # print(markdown_content)    
    export_to_html_and_pdf(markdown_content, output_base=base_filename)
