import os
from datetime import datetime

import matplotlib
matplotlib.use("Agg")  # important for batch/report generation (no display)

import rwe.utils.helpers as uth
import rwe.utils.report as utr
import rwe.utils.presentation as upp
from rwe.utils.keywords import disease_to_keywords


# ---------- Main user-facing function ----------

def generate_rwe_report(
    gene: str,
    chrm: str,
    out_docx_path: str = "",
    logo_path: str = "",
    report_date: str = "",
    indications: str = "",
    allofus: bool = True,
    genebass: bool = True,
    astrazeneca: bool = True,
    generate_pptx: bool = True,
):
    """
    Creates a DOCX report and optionally a PPTX report with:
      - Title page
      - Contents (TOC field)
      - Five section headers
      - Variant information + Demographics figures inserted into section 1

    Parameters
    ----------
    gene : str
    chrm : str
    out_docx_path : str
    logo_path : optional str (path to Arrowhead logo PNG/JPG)
    report_date : optional str (e.g. "January 26th, 2026")
    indications : optional str (e.g. "obesity,diabetes")
    generate_pptx : bool
        If True, also generate a PowerPoint summary using the template.
    """
    if not out_docx_path:
        date_tag = datetime.today().strftime("%m%d%y")
        out_docx_path = f"./data/rwe_reports/{gene}/RWE_{gene}_report_{date_tag}.docx"
    proj_dir = os.path.dirname(out_docx_path) or f"./data/rwe_reports/{gene}"
    os.makedirs(proj_dir, exist_ok=True)
    uth._set_figure_save_context(proj_dir, gene)

    try:
        # --- Title and Contents --- #
        doc = utr.generate_title_and_contents(gene, logo_path=logo_path, report_date=report_date)

        # --- Variant information and demographics --- #
        doc = utr.generate_variant_information_and_demographics(doc, chrm, gene, "hetz", allofus=allofus)

        # --- Clinical records --- #
        doc = utr.generate_clinical_records(doc, chrm, gene, "hetz", proj_dir, allofus=allofus, genebass=genebass, astrazeneca=astrazeneca)
        
        # --- Labs and measurements --- #
        doc = utr.generate_labs_and_measurements(doc, chrm, gene, "hetz", proj_dir, allofus=allofus, genebass=genebass, astrazeneca=astrazeneca)

        # --- Survey information --- #
        doc = utr.generate_survey_information(doc, chrm, gene, "hetz", proj_dir, allofus=allofus)

        # --- Homozygous loss of function carriers --- #
        doc = utr.generate_homozygous_lof_carriers(doc, chrm, gene, proj_dir, allofus=allofus)

        # --- Plasma proteomics --- #
        doc = utr.generate_plasma_proteomics_report(doc, chrm, gene, proj_dir, astrazeneca=astrazeneca)

        # --- Indication-specific report --- #
        indications_list = []
        if indications:
            indications_list = [i.strip() for i in indications.split(",")]
            keywords = sum([disease_to_keywords[i] for i in indications_list if i in disease_to_keywords], [])
            if keywords:
                doc = utr.generate_indication_specific_report(doc, chrm, gene, proj_dir, indications_list, keywords, allofus=allofus, genebass=genebass, astrazeneca=astrazeneca)
            else:
                print(f"Warning: no keywords found for indications {indications_list}; skipping indication-specific report")

        # --- End of report --- #
        doc = utr.generate_end_of_report(doc)

        # Save
        doc.save(out_docx_path)

        out_pptx_final = ""
        if generate_pptx:
            out_pptx_final = upp.generate_rwe_presentation(
                gene=gene,
                indications=indications_list if indications_list else indications,
                output_dir=proj_dir,
                report_date=report_date,
                allofus=allofus,
                astrazeneca=astrazeneca,
                genebass=genebass,
            )
        return {"docx_path": out_docx_path, "pptx_path": out_pptx_final}
    finally:
        uth._clear_figure_save_context()

if __name__ == "__main__":
    pass
