import matplotlib.pyplot as plt, tempfile, os
from pptx import Presentation
from pptx.util import Inches

def make_charts(table):
    labels = [r['label'] for r in table]
    comp   = [r['company'] for r in table]
    bench  = [r['benchmark'] if r['benchmark'] is not None else 0 for r in table]

    # bar chart
    plt.figure(figsize=(10,4))
    x = range(len(labels))
    plt.bar(x, comp, label="Azienda")
    plt.bar(x, bench, bottom=comp, label="Benchmark")
    plt.xticks(x, labels, rotation=45, ha='right')
    plt.legend(); plt.tight_layout()
    png_bar = tempfile.NamedTemporaryFile(delete=False, suffix='.png').name
    plt.savefig(png_bar, dpi=180); plt.close()
    return png_bar

def build_pptx(answer_id, narrative, png_bar):
    prs = Presentation("templates/smartweek_template_ready.pptx")

    # slide 7 → inserisci grafico come immagine
    slide7 = prs.slides[6]
    slide7.shapes.add_picture(png_bar, Inches(1), Inches(1.5), Inches(8), Inches(4))

    # slide 8 → inserisci testo GPT
    slide8 = prs.slides[7]
    tf = slide8.shapes[1].text_frame
    tf.clear()
    tf.text = narrative

    out = f"/var/www/html/ai_worker/reports/report_{answer_id}.pptx"
    prs.save(out)
    return out

def save_chart_png(table, answer_id):
    labels = [r['label'] for r in table]
    comp   = [r['company'] for r in table]
    bench  = [r['benchmark'] if r['benchmark'] is not None else 0 for r in table]

    import matplotlib.pyplot as plt
    import os

    fig, ax = plt.subplots(figsize=(10, 4))
    x = range(len(labels))
    ax.bar(x, comp, label="Azienda")
    ax.bar(x, bench, bottom=comp, label="Benchmark")
    ax.set_xticks(x)
    ax.set_xticklabels(labels, rotation=45, ha='right')
    ax.legend(); plt.tight_layout()

    path = f"/var/www/html/ai_worker/exports/chart_{answer_id}.png"
    plt.savefig(path)
    plt.close()
    return path

def render_html_table(table):
    rows = ""
    for r in table:
        bmk = r['benchmark'] if r['benchmark'] is not None else "-"
        rows += f"<tr><td>{r['label']}</td><td>{r['company']}</td><td>{bmk}</td></tr>"
    html = f"""
    <table class='table table-striped'>
      <thead><tr><th>Fattore</th><th>Azienda</th><th>Benchmark</th></tr></thead>
      <tbody>{rows}</tbody>
    </table>
    """
    return html


