#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os
import re
import logging
import datetime
import json
import unicodedata
import smtplib
import httpx
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate

# Configure logging
logging.basicConfig(
    filename='/var/log/lateNotice.log',
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

#------------------------------------------------
# Configuration Variables
#------------------------------------------------
URL = 'https://demo.wyzio.com'
TOKEN = 'ffffffff-ffff-ffff-ffff-ffffffffffff'
MAIL_SERVER = '10.10.10.10'
ORGANIZATION_NAME = 'Acme SA'
NB_DAYS_FOR_LATE_NOTICE_1 = 20
NB_DAYS_FOR_LATE_NOTICE_2 = 10
NB_DAYS_FOR_LATE_NOTICE_3 = 5
LEVEL_OF_ACCEPTANCE = 3
DEFAULT_EMAIL_ADDRESS = 'abc@def.com'
SEND_FROM_EMAIL = 'abc@def.com'

#------------------------------------------------
# Helper Functions
#------------------------------------------------
def get_overdue_invoices(organization_id):
    headers = {
        'User-Agent': 'Wyzio/1.0',
        'weal-token': TOKEN,
        'cache-control': 'no-cache',
        'target-organization-id': str(organization_id)
    }
    service_url = f"{URL}/api-v1/late-notice/client?sizePerPage=10000&sortingField=overdueAmount&direction=DESC&organizationId={organization_id}"
    try:
        response = httpx.get(service_url, headers=headers, timeout=10)
        return response.json()
    except Exception as e:
        logging.warning(f"Failed to get overdue invoices for organization {organization_id}: {e}")
        return []


def get_invoice_details(organization_id, invoice_number):
    headers = {
        'User-Agent': 'Wyzio/1.0',
        'weal-token': TOKEN,
        'cache-control': 'no-cache',
        'target-organization-id': str(organization_id)
    }
    service_url = f"{URL}/api-v1/sales-invoice?number={invoice_number}"
    try:
        response = httpx.get(service_url, headers=headers, timeout=10)
        return response.json()
    except Exception as e:
        logging.warning(f"Cannot get invoice details for invoice {invoice_number}: {e}")
        return []


def send_mail(send_from, send_to, subject, html_content, pdf_file, smtp_server=MAIL_SERVER):
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    # Attach HTML content
    msg.attach(MIMEText(html_content, "html", "utf-8"))

    # Attach PDF file
    try:
        with open(pdf_file, "rb") as f:
            part = MIMEApplication(f.read(), _subtype='pdf')
            part.add_header('Content-Disposition', 'attachment', filename=basename(pdf_file))
        msg.attach(part)
    except Exception as e:
        logging.warning(f"Could not attach PDF file {pdf_file}: {e}")
        return

    try:
        with smtplib.SMTP(smtp_server, 587) as smtp:
            smtp.set_debuglevel(1)
            smtp.ehlo()
            smtp.starttls()
            smtp.ehlo()
            smtp.login("email", "password")
            smtp.sendmail(send_from, send_to, msg.as_string())
    except Exception as e:
        logging.warning(f"Failed to send mail to {send_to}: {e}")


def determine_language_fields(lang, invoice_number):
    """Return subject, text, footer, invoice label, due date label, and status label based on language."""
    if lang.upper() == 'FR':
        return (
            f'Rappel concernant la facture {invoice_number}',
            'Cher client,Veuillez trouver en annexe un rappel concernant une facture impayée.',
            'Meilleures salutations,Votre équipe Wyzio',
            'Facture # :',
            'Date de facture: ',
            'Statut: '
        )
    elif lang.upper() == 'DE':
        return (
            f'Verspätete Benachrichtigung für Rechnung {invoice_number}',
            'Sehr geehrter Kunde,Bitte finden Sie im Anhang eine Verspätungsbescheid über eine unbezahlte Rechnung.',
            'Besondere Grüße,Ihr Wyzio Team',
            'Rechnung # :',
            'Rechnungsdatum: ',
            'Status: '
        )
    elif lang.upper() == 'IT':
        return (
            f'Avviso in ritardo per la fattura {invoice_number}',
            'Gentile cliente,Si prega di trovare in allegato un avviso tardivo relativo a una fattura non pagata.',
            'Ti migliori saluti,Il vostro team Wyzio',
            'Fattura # :',
            'Data fattura: ',
            'Stato:  '
        )
    else:
        # Default to English
        return (
            f'Late Notice for invoice {invoice_number}',
            "Dear customer,Please find attached a late notice concerning an unpaid invoice.Best regards,Your Wyzio's Team",
            'Best regards,Your Wyzio\'s Team',
            'Invoice # :',
            'Invoice date: ',
            'Status: '
        )


def format_email_text(subject, text, currency, total_amount, status_label, invoice_status, due_date_label, invoice_date, footer):
    # Replace HTML  with newlines in text and footer and add additional invoice details
    plain_text = text.replace('', '\n\n')
    plain_footer = footer.replace('', '\n')
    additional_info = f"\n\nTotal ({currency}): {total_amount}\n{status_label.replace('','')}{invoice_status}\n{due_date_label}{invoice_date}\n\n{plain_footer}"
    return plain_text + additional_info


#------------------------------------------------
# Main Script Logic
#------------------------------------------------
def main():
    # Use common headers for organization lookup
    common_headers = {'User-Agent': 'Wyzio/1.0', 'weal-token': TOKEN, 'cache-control': 'no-cache'}
    org_service = f"{URL}/api-v1/organization?name={ORGANIZATION_NAME}"
    try:
        response = httpx.get(org_service, headers=common_headers, timeout=10)
    except Exception as e:
        logging.warning(f"Cannot connect to server: {e}")
        sys.exit("Cannot connect to server!")
    try:
        organization_id = response.json()[0]['id']
    except Exception as e:
        logging.warning(f"Organization {ORGANIZATION_NAME} does not exist: {e}")
        sys.exit(f"Organization {ORGANIZATION_NAME} does not exist!")

    # Use headers with organization target for subsequent requests
    org_headers = {
        'User-Agent': 'Wyzio/1.0',
        'weal-token': TOKEN,
        'cache-control': 'no-cache',
        'target-organization-id': str(organization_id)
    }

    # Set up deadlines for late notices
    now = datetime.datetime.now()
    deadline1 = now - datetime.timedelta(days=NB_DAYS_FOR_LATE_NOTICE_1)
    deadline2 = now - datetime.timedelta(days=NB_DAYS_FOR_LATE_NOTICE_2)
    deadline3 = now - datetime.timedelta(days=NB_DAYS_FOR_LATE_NOTICE_3)

    logging.warning("Start of late notices check!")
    overdue_invoices = get_overdue_invoices(organization_id)
    logging.info(f"{len(overdue_invoices)} late notices to look at!")

    for invoice in overdue_invoices:
        unacceptable = False
        do_not_send = False
        invoice_number = invoice.get('salesInvoiceNumber')
        logging.info(f"Should generate a late notice for invoice {invoice_number}!")

        notice_qty = invoice.get('noticeGeneratedQuantity', 0)
        try:
            if notice_qty == 0:
                deadline = deadline1
                last_notice_date = datetime.datetime.strptime(invoice['overdueDate'][:10], '%Y-%m-%d')
                if LEVEL_OF_ACCEPTANCE == 1:
                    unacceptable = True
            elif notice_qty == 1:
                deadline = deadline2
                last_notice_date = datetime.datetime.strptime(invoice['lastNoticeGeneratedDate'][:10], '%Y-%m-%d')
                if LEVEL_OF_ACCEPTANCE == 2:
                    unacceptable = True
            elif notice_qty == 2:
                deadline = deadline3
                last_notice_date = datetime.datetime.strptime(invoice['lastNoticeGeneratedDate'][:10], '%Y-%m-%d')
                if LEVEL_OF_ACCEPTANCE == 3:
                    unacceptable = True
            elif notice_qty >= 3:
                do_not_send = True
            else:
                deadline = deadline1
                last_notice_date = datetime.datetime.strptime(invoice['overdueDate'][:10], '%Y-%m-%d')
        except Exception as e:
            logging.warning(f"Error parsing notice dates for invoice {invoice_number}: {e}")
            continue

        if last_notice_date < deadline and not do_not_send:
            logging.info(f"Will generate a late notice for invoice {invoice_number}!")
            invoice_details = get_invoice_details(organization_id, invoice_number)
            if not invoice_details:
                continue

            try:
                inv = invoice_details[0]
                # Extract invoice details; assume these fields exist
                currency = inv['currency']
                total_amount = str(inv['totalAmount'])
                invoice_date = str(inv['date'])[:10]
                invoice_status = inv['status']

                # Get client contact details
                client_service = f"{URL}/api-v1/contact?id={invoice.get('clientContactId')}"
                client = httpx.get(client_service, headers=org_headers, timeout=10).json()
                if client:
                    contact_service = f"{URL}/api-v1/contact/{client[0]['contactType']}/{client[0]['id']}"
                    client_details = httpx.get(contact_service, headers=org_headers, timeout=10).json()
                    send_to = client_details.get('email') or 'NONE'
                    lang = client_details.get('defaultLanguage', 'EN')
                else:
                    logging.warning(f"Cannot get client id for contact {invoice.get('clientContactId')}")
                    send_to = 'NONE'
                    lang = 'EN'

                # Set language-dependent email content
                subject, text, footer, invoice_label, due_date_label, status_label = determine_language_fields(lang, invoice_number)

                # If unacceptable or missing email, override recipient
                if unacceptable or send_to == 'NONE':
                    send_to = 'litigation@wyzio.com'

                # Create plain-text email body from HTML parts
                email_body = format_email_text(subject, text, currency, total_amount, status_label, invoice_status, due_date_label, invoice_date, footer)

                # Build PDF generation URL
                now_str = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%dT%H:%M:%S.000Z')
                pdf_service = (
                    f"{URL}/api-v1/generate-pdf?useLetterhead=true&overdueDate=%3C{now_str}"
                    f"&id={invoice.get('id')}&organizationId={organization_id}&type=LATE_NOTICE"
                    f"&lateNoticePdfType=REMINDER&increaseLateNoticeNumber=true"
                )
                try:
                    pdf_response = httpx.get(pdf_service, headers=org_headers, timeout=10)
                    if pdf_response.status_code == 200:
                        pdf_file = f"/tmp/{inv.get('number', invoice_number)}.pdf"
                        with open(pdf_file, 'wb') as f:
                            f.write(pdf_response.content)
                    else:
                        logging.warning(f"PDF generation failed for invoice {invoice_number}")
                        continue
                except Exception as e:
                    logging.warning(f"Error generating PDF for invoice {invoice_number}: {e}")
                    continue

                try:
                    send_mail(SEND_FROM_EMAIL, send_to, subject, email_body, pdf_file)
                    logging.warning(f"The late notice for invoice {invoice_number} was sent!")
                except Exception as e:
                    logging.warning(f"Could not send late notice for invoice {invoice_number}: {e}")
                try:
                    os.remove(pdf_file)
                except Exception:
                    pass

            except Exception as e:
                logging.warning(f"Error processing invoice {invoice_number}: {e}")

    logging.warning("End of late notices check!")


if __name__ == "__main__":
    main()