from reportlab.platypus import SimpleDocTemplate
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import mm
from facturx import generate_from_file
from ...models.models import DevisData
from .styles import get_styles
from .template_default import items_table, draw_footer, draw_header, \
    four_columns_block, partner, invoice_description, summary_tables

from importlib import resources
import os

def generate_invoice(file_name: str, destination_folder:str, data: dict, title,logopath=resources.files("ads_facturx.Builders.pdf.logo").joinpath("ads-logo.png")):
    """
    Generates a quotation based on a raw data structure
    :param file_name: Path to the output file.
    :param data: Raw data structure used to generate the quotation.
    :param logopath: Path to the invoice logo.
    :return: None
    """
    # 1. Validation des données
    validated = DevisData.model_validate(data)

    # Create destination folder if it does not exist
    os.makedirs(destination_folder, exist_ok=True)

    # Full file path
    file_path = os.path.join(destination_folder, file_name)

    logo = logopath
    # 2. Création du document (réservation espace footer)
    HEADER_HEIGHT = 25 * mm
    FOOTER_HEIGHT = 30 * mm
    doc = SimpleDocTemplate(
        file_path,
        title = title,
        author="Alchimie Data Solutions",
        creator = "Alchimie Data Solutions",
        pagesize=A4,
        rightMargin=10*mm,
        leftMargin=10*mm,
        topMargin=HEADER_HEIGHT + 20*mm,
        bottomMargin=FOOTER_HEIGHT + 10*mm
    )

    styles = get_styles()
    elements = []

    # 3. Contenu "normal" (flux)
    partner(elements, styles, validated)
    four_columns_block(elements, styles,validated)
    items_table(elements, styles,validated)
    summary_tables(elements,data)
    invoice_description(elements, styles,validated)


    # 4. Callback header et footer
    def _header_footer(canvas, doc,logo):

        draw_header(canvas, doc, validated.company,logo)
        draw_footer(canvas, doc, validated.footer)


    # 5. Construction finale du PDF
    doc.build(
        elements,
        onFirstPage=lambda c, d: _header_footer(c, d, logo),
        onLaterPages=lambda c, d: _header_footer(c, d, logo)
    )

def generate_facturx(file_name:str, destination_folder:str, xml):
    file_path = os.path.join(destination_folder, file_name)
    return generate_from_file(file_path,xml)