import os
import pandas as pd

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

import rwe.utils.report as utr



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

def generate_rwe_report(
    gene: str,
    chrm: str,
    zygosity: str = "hetz",
    out_docx_path: str = "",
    logo_path: str = "",
    report_date: str = "",
):
    """
    Creates a DOCX 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")
    """
    if not out_docx_path:
        out_docx_path = f"./rwe_reports/{gene}_RWE_report.docx"
    proj_dir = os.path.dirname(out_docx_path)
    os.makedirs(proj_dir, exist_ok=True)

    # --- 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, zygosity)

    # --- Clinical records --- #
    doc = utr.generate_clinical_records(doc, chrm, gene, zygosity, proj_dir)
    
    # --- Labs and measurements --- #
    doc = utr.generate_labs_and_measurements(doc, chrm, gene, zygosity, proj_dir)

    # --- Survey information --- #
    doc = utr.generate_survey_information(doc, chrm, gene, zygosity, proj_dir)

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


    # Save
    doc.save(out_docx_path)
    return out_docx_path

if __name__ == "__main__":
    import pandas as pd

