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

import httpx
import sys
import json
import logging
import datetime
import unicodedata
import calendar

logging.basicConfig(
    filename='/var/log/generateInterestInvoices.log',
    level=logging.WARNING,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

#------------------------------------------------
# Helper Functions
#------------------------------------------------
def get_new_details(journal_entries, start_date_range, end_date_range, rate, delay=0):
    """
    Compute interest details for a list of journal entries.
    Returns a list where every two elements represent a description and an interest amount.
    """
    new_invoice_line_list = []
    total_entries = len(journal_entries)
    
    # Pre-calculate the parsed start/end range dates for comparison
    start_range_dt = datetime.datetime.strptime(start_date_range[:10], '%Y-%m-%d')
    end_range_dt   = datetime.datetime.strptime(end_date_range[:10], '%Y-%m-%d')
    
    for d, entry in enumerate(journal_entries):
        try:
            principal = float(entry['companyTotal'])
        except Exception as e:
            logging.warning(f"Error parsing companyTotal for entry {d}: {e}")
            continue

        # Determine start date for the period
        if d == 0:
            start_date = start_range_dt + (datetime.timedelta(days=30) if delay else datetime.timedelta(0))
        else:
            entry_date = datetime.datetime.strptime(entry['entryDate'][:10], '%Y-%m-%d')
            start_date = entry_date + (datetime.timedelta(days=30) if delay else datetime.timedelta(0))

        # Determine end date for the period
        if total_entries == 1 or d == total_entries - 1:
            end_date = end_range_dt
        else:
            end_date = datetime.datetime.strptime(journal_entries[d + 1]['entryDate'][:10], '%Y-%m-%d')

        # If the period covers the full range, use a fixed duration of 90 days; otherwise, compute the difference
        if start_date == start_range_dt and end_date == end_range_dt:
            nb_days = 90
        else:
            nb_days = (end_date - start_date).days
            if d == total_entries - 1:
                nb_days += 1

        nb_days = max(0, min(nb_days, 90))  # Ensure nb_days is between 0 and 90

        if principal > 0 and nb_days > 0 and rate > 0:
            # Round interest to the nearest 0.05 (i.e. increments of 20)
            interest = round(principal * rate * nb_days / 365 * 20) / 20
            description = (
                f"Intérêts de {rate * 100}% sur CHF {'{:,}'.format(principal)} du "
                f"{start_date.strftime('%d-%m-%Y')} au {end_date.strftime('%d-%m-%Y')}, soit {nb_days} jours"
            )
            new_invoice_line_list.extend([description, interest])
    
    return new_invoice_line_list

def new_line_detail(detail, account, temp_id):
    """
    Build a new invoice line detail dictionary.
    Returns a tuple of (line dictionary, interest amount).
    """
    new_detail = {
        "discount": 0,
        "saleAccountId": account,
        "vatRateId": None,
        "totalPrice": detail['interest'],
        "netUnitPrice": 1,
        "vat": None,
        "quantity": detail['interest'],
        "departmentId": None,
        "lineType": "ARTICLE",
        "articleId": 65475909,
        "totalNet": detail['interest'],
        "id": None,
        "description": detail['description'],
        "allocationKey": None,
        "appliedAllocationRules": [],
        "tempId": str(temp_id)
    }
    return new_detail, detail['interest']

def new_line_layout(temp_id):
    """
    Build a new invoice line layout dictionary.
    """
    return {
        "children": None,
        "parentId": None,
        "position": temp_id + 3,
        "name": None,
        "lineType": "NO_ARTICLE",
        "tempId": str(temp_id),
        "salesInvoiceLineId": str(temp_id + 1),
        "collapsed": False,
        "id": str(temp_id),
        "leaf": False
    }

#------------------------------------------------
# Configuration Variables
#------------------------------------------------
url = 'https://demo.wyzio.com'
token = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
headers = {
    'User-Agent': 'Wyzio/1.0',
    'weal-token': token,
    'cache-control': 'no-cache'
}

today = datetime.datetime.now()
month = int(today.strftime('%m'))
year = today.strftime('%Y')
time_suffix = 'T00:00:00.000Z'
overdue_date = today.replace(day=calendar.monthrange(today.year, today.month)[1])
overdue_date = overdue_date.strftime('%Y-%m-%d') + time_suffix

rate = 0.05

# Determine date ranges based on current month (quarterly periods)
if month <= 3:
    start_date_range = f"{int(year)-1}-10-01" + time_suffix
    end_date_range   = f"{int(year)-1}-12-31" + time_suffix
elif month <= 6:
    start_date_range = year + "-01-01" + time_suffix
    end_date_range   = year + "-03-31" + time_suffix
elif month <= 9:
    start_date_range = year + "-04-01" + time_suffix
    end_date_range   = year + "-06-30" + time_suffix
else:
    start_date_range = year + "-07-01" + time_suffix
    end_date_range   = year + "-09-30" + time_suffix

new_invoice_date = end_date_range

# Get organization info
org_service = f"{url}/api-v1/organization?name=Acme Ltd."
try:
    response = httpx.get(org_service, headers=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 Acme Ltd. does not exist: {e}")
    sys.exit("Organization Acme Ltd. does not exist!")

# (Override organization_id if necessary)
organization_id = '999999999999999'

headers = {
    'weal-token': token,
    'cache-control': 'no-cache',
    'target-organization-id': organization_id,
    'Content-Type': 'application/json'
}

# Get customer list
customer_service = f"{url}/api-v1/contact?sizePerPage=10000&isCustomer=true"
try:
    customer_list = httpx.get(customer_service, headers=headers, timeout=10).json()
except Exception as e:
    logging.warning(f"Cannot get list of customers: {e}")
    customer_list = []

# Get account details
def fetch_account(account_number, label):
    service = f"{url}/api-v1/chart-accounts?accountNumber={account_number}"
    try:
        resp = httpx.get(service, headers=headers, timeout=10).json()
        return str(resp[0]['id'])
    except Exception as e:
        logging.warning(f"Cannot get {label} detail: {e}")
        return None

accounting_account = fetch_account(44021, "accounting account")
BL_account = fetch_account(10204, "BL account")
payment_account = fetch_account(10011, "payment account")

logging.info(f"{len(customer_list)} customer(s) to treat.")

#------------------------------------------------
# Main Processing Loop
#------------------------------------------------
new_invoice_list = []  # Not used later; could be removed if not needed

for customer in customer_list:
    customer_id = customer['id']
    customer_name = customer['name']
    
    # Fetch ledger details for various accounts for the customer within the date range
    def fetch_ledger(account):
        service = (f"{url}/api-v1/ledger?contactIds={customer_id}&account={account}"
                   f"&entryDate={start_date_range}..{end_date_range}&pageNumber=1"
                   f"&isBalanceCarried=true&sortingField=entryDate&direction=ASC"
                   f"&sizePerPage=10000&isAppRequest=true")
        try:
            return httpx.get(service, headers=headers, timeout=10).json()
        except Exception as e:
            logging.warning(f"Cannot get total of account {account} for customer {customer_name}: {e}")
            return []
    
    account10200 = fetch_ledger(10200)
    account10201 = fetch_ledger(10201)
    account10204 = fetch_ledger(10204)
    
    # Sum the totals from the last ledger entry of each account if available
    total_due = 0
    for ledger in (account10200, account10201, account10204):
        if ledger:
            total_due += ledger[-1].get('companyTotal', 0)
    
    if total_due > 0:
        new_invoice_line_list = []
        new_invoice_line_list.extend(get_new_details(account10200, start_date_range, end_date_range, rate))
        new_invoice_line_list.extend(get_new_details(account10201, start_date_range, end_date_range, rate))
        new_invoice_line_list.extend(get_new_details(account10204, start_date_range, end_date_range, rate, delay=1))
        
        # Build a list of details from pairs of (description, interest)
        new_detail = [
            {'description': desc, 'interest': interest}
            for desc, interest in zip(new_invoice_line_list[0::2], new_invoice_line_list[1::2])
        ]
        
        if new_detail:
            # Get client contact detail
            contact_service = f"{url}/api-v1/contact/{customer_id}/client"
            try:
                contact_detail = httpx.get(contact_service, headers=headers, timeout=10).json()
            except Exception as e:
                logging.warning(f"Cannot get client detail for customer {customer_name}: {e}")
                continue
            
            # Find invoice address matching invoiceAddressId, otherwise use first address
            address = None
            for addr in contact_detail.get('addresses', []):
                if addr.get('id') == contact_detail.get('invoiceAddressId'):
                    address = addr
                    break
            if address is None and contact_detail.get('addresses'):
                address = contact_detail['addresses'][0]
            if address:
                address['id'] = None  # Reset address id
            
            new_invoice = [{
                "id": None,
                "clientAddressId": contact_detail.get('invoiceAddressId'),
                "clientId": customer_id,
                "comments": None,
                "currencyId": 1214,
                "date": new_invoice_date,
                "timesheetInfoItems": [],
                "excludedFromVat": False,
                "receivableAccountId": BL_account,
                "vatTypeCodeId": None,
                "clientName": customer_name,
                "description": f"Intérêts au {datetime.datetime.strptime(end_date_range[:10],'%Y-%m-%d').strftime('%d-%m-%Y')}",
                "address": address,
                "invoiceLines": [],
                "invoiceLinesLayout": [],
                "number": None,
                "reference": None,
                "shipments": [],
                "payments": [{
                    "bankCharges": 0,
                    "paidAmount": 0,
                    "requestedAmount": 0,
                    "overdueDate": overdue_date,
                    "receivableByAccountId": payment_account,
                    "id": None,
                    "lossOnDebtors": 0,
                    "requestedDate": overdue_date,
                    "valueDate": None
                }],
                "warnings": None
            }]
            
            total_amount = 0
            index = 0
            new_invoice_line = []
            new_layout = []
            
            for detail in new_detail:
                index -= 1
                line, total = new_line_detail(detail, accounting_account, index)
                new_invoice_line.append(line)
                total_amount += float(total)
                index -= 1
                new_layout.append(new_line_layout(index))
            
            if total_amount > 1:
                new_invoice[0]['invoiceLines'] = new_invoice_line
                new_invoice[0]['invoiceLinesLayout'] = new_layout
                requested_amount = f"{total_amount:.2f}"
                new_invoice[0]['payments'][0]['requestedAmount'] = requested_amount

                # Post the new interest invoice
                invoice_service = f"{url}/api-v1/sales-invoice/batch"
                try:
                    post_response = httpx.post(invoice_service, data=json.dumps(new_invoice), headers=headers, timeout=10).json()
                    if post_response.get('items', [{}])[0].get('errorCode', {}).get('errorCode') == 'NO_ERROR':
                        logging.debug(f"New interest invoice for {customer_name} was successfully created!")
                    else:
                        logging.warning(f"Could not insert interest invoice for {customer_name}!")
                except Exception as e:
                    logging.warning(f"Could not insert interest invoice for {customer_name}: {e}")

# End of processing
logging.info("Finished processing interest invoices.")