"""Regenerate the fictional invoice form/report examples and their shared caption seed."""
from pathlib import Path
import json

ROOT = Path(__file__).resolve().parent.parent
LANGS = ['en', 'de', 'fr', 'es', 'it']
CAPTIONS = {
 'incoming': ['Incoming invoice', 'Eingangsrechnung', 'Facture fournisseur', 'Factura recibida', 'Fattura di acquisto'],
 'outgoing': ['Outgoing invoice', 'Ausgangsrechnung', 'Facture client', 'Factura emitida', 'Fattura di vendita'],
 'details': ['Invoice details', 'Rechnungsdaten', 'Détails de la facture', 'Datos de factura', 'Dati fattura'],
 'number': ['Invoice number', 'Rechnungsnummer', 'Numéro de facture', 'Número de factura', 'Numero fattura'],
 'date': ['Invoice date', 'Rechnungsdatum', 'Date de facture', 'Fecha de factura', 'Data fattura'],
 'dueDate': ['Due date', 'Fällig am', "Date d’échéance", 'Vencimiento', 'Scadenza'],
 'currency': ['Currency', 'Währung', 'Devise', 'Moneda', 'Valuta'],
 'supplier': ['Supplier', 'Lieferant', 'Fournisseur', 'Proveedor', 'Fornitore'],
 'customer': ['Customer', 'Kunde', 'Client', 'Cliente', 'Cliente'],
 'company': ['Company', 'Firma', 'Société', 'Empresa', 'Azienda'],
 'address': ['Address', 'Anschrift', 'Adresse', 'Dirección', 'Indirizzo'],
 'email': ['Email', 'E-Mail', 'Courriel', 'Correo electrónico', 'Email'],
 'partnerId': ['Partner reference', 'Partnernummer', 'Référence partenaire', 'Referencia del socio', 'Riferimento partner'],
 'lines': ['Invoice lines', 'Rechnungspositionen', 'Lignes de facture', 'Líneas de factura', 'Righe fattura'],
 'position': ['No.', 'Pos.', 'N°', 'N.º', 'N.'],
 'description': ['Description', 'Beschreibung', 'Description', 'Descripción', 'Descrizione'],
 'quantity': ['Quantity', 'Menge', 'Quantité', 'Cantidad', 'Quantità'],
 'unitPrice': ['Unit price', 'Einzelpreis', 'Prix unitaire', 'Precio unitario', 'Prezzo unitario'],
 'vatRate': ['VAT %', 'USt. %', 'TVA %', 'IVA %', 'IVA %'],
 'account': ['Account', 'Sachkonto', 'Compte', 'Cuenta', 'Conto'],
 'costCenter': ['Cost center', 'Kostenstelle', 'Centre de coûts', 'Centro de costes', 'Centro di costo'],
 'accounting': ['Accounting', 'Buchhaltung', 'Comptabilité', 'Contabilidad', 'Contabilità'],
 'postingDate': ['Posting date', 'Buchungsdatum', 'Date comptable', 'Fecha contable', 'Data registrazione'],
 'journal': ['Journal', 'Buchungsjournal', 'Journal', 'Diario', 'Giornale'],
 'balanceAccount': ['Partner account', 'Personenkonto', 'Compte partenaire', 'Cuenta del socio', 'Conto partner'],
 'taxAccount': ['VAT account', 'Steuerkonto', 'Compte TVA', 'Cuenta IVA', 'Conto IVA'],
 'reference': ['Reference', 'Referenz', 'Référence', 'Referencia', 'Riferimento'],
 'notes': ['Notes', 'Notizen', 'Notes', 'Notas', 'Note'],
 'net': ['Net amount', 'Nettobetrag', 'Montant HT', 'Importe neto', 'Imponibile'],
 'tax': ['VAT amount', 'Steuerbetrag', 'Montant TVA', 'Importe IVA', 'Importo IVA'],
 'gross': ['Total amount', 'Gesamtbetrag', 'Montant TTC', 'Importe total', 'Importo totale'],
 'debit': ['Debit', 'Soll', 'Débit', 'Debe', 'Dare'],
 'credit': ['Credit', 'Haben', 'Crédit', 'Haber', 'Avere'],
 'payables': ['Trade payables', 'Verbindlichkeiten', 'Dettes fournisseurs', 'Deudas comerciales', 'Debiti fornitori'],
 'receivables': ['Trade receivables', 'Forderungen', 'Créances clients', 'Créditos comerciales', 'Crediti clienti'],
 'demo': ['Fictional example for demonstration only', 'Fiktives Beispiel für Demonstrationszwecke', 'Exemple fictif de démonstration', 'Ejemplo ficticio de demostración', 'Esempio fittizio dimostrativo'],
}

def write(path, value):
 path.parent.mkdir(parents=True, exist_ok=True)
 path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')

def item(kind, name, caption, **extra):
 return {'id': f'{kind}_{name}', 'type': kind, 'name': name, 'label': CAPTIONS[caption][0], 'captionKey': 'invoice.' + caption, 'span': 6, **extra}

def generate():
 caption_file = ROOT / 'data/ecm/translations.json'
 catalog = json.loads(caption_file.read_text(encoding='utf-8-sig')) if caption_file.exists() else {'languages': LANGS + ['cs', 'sk'], 'entries': {}}
 for key, values in CAPTIONS.items(): catalog['entries']['invoice.' + key] = dict(zip(LANGS, values))
 write(caption_file, catalog)
 for incoming in [True, False]:
  direction = 'incoming' if incoming else 'outgoing'
  party = 'supplier' if incoming else 'customer'
  lines = [{'description': 'Demonstration supplies' if incoming else 'Demonstration consulting', 'quantity': 2 if incoming else 3, 'unitPrice': 125 if incoming else 120, 'vatRate': 20, 'account': '6000' if incoming else '4000', 'costCenter': 'DEMO-01'},
           {'description': 'Demonstration support' if incoming else 'Demonstration setup', 'quantity': 1, 'unitPrice': 80 if incoming else 90, 'vatRate': 20, 'account': '6100' if incoming else '4000', 'costCenter': 'DEMO-01'}]
  columns = [item('number' if name in ['quantity', 'unitPrice', 'vatRate'] else 'text', name, name, **({'min': 0.001, 'step': 0.001} if name == 'quantity' else {'min': 0, 'step': 0.01} if name == 'unitPrice' else {'min': 0, 'max': 100, 'step': 0.01} if name == 'vatRate' else {})) for name in ['description','quantity','unitPrice','vatRate','account','costCenter']]
  design = {'title': CAPTIONS[direction][0], 'titleKey': 'invoice.' + direction, 'description': CAPTIONS['demo'][0], 'descriptionKey': 'invoice.demo', 'layout': 'wizard', 'sampleKind': direction + 'Invoice', 'report': {'engine': 'fop', 'template': f'invoices/{direction}-invoice.fo'}, 'items': [
   item('step','', 'details', items=[
    item('group','header','details',span=12,items=[item('text','number','number',required=True,default=('IN' if incoming else 'OUT')+'-DEMO-001'),item('date','date','date',required=True,default='2026-10-26'),item('date','dueDate','dueDate',required=True,default='2026-11-09'),item('select','currency','currency',options=['EUR','USD','GBP'],default='EUR')]),
    item('group','party',party,span=12,items=[item('text','company','company',required=True,default='Fake Company' if incoming else 'Baerenstahl Demo'),item('text','partnerId','partnerId',default='DEMO-PARTNER-01'),item('email','email','email',required=True,default='office@fakecompany.eu' if incoming else 'office@baerenstahl.dev'),item('textarea','address','address',default='Demonstration Avenue 1\n10000 Example City',rows=2)])]),
   item('step','','lines',items=[item('table','lines','lines',span=12,required=True,minRows=1,maxRows=200,columns=columns,default=lines),item('textarea','notes','notes',span=12,rows=3,default='Synthetic sample data. No real transaction.')]),
   item('step','','accounting',items=[item('group','accounting','accounting',span=12,items=[item('date','postingDate','postingDate',required=True,default='2026-10-26'),item('text','journal','journal',required=True,default='PURCHASE-DEMO' if incoming else 'SALES-DEMO'),item('text','balanceAccount','balanceAccount',required=True,default='3300' if incoming else '2000'),item('text','taxAccount','taxAccount',required=True,default='2500' if incoming else '3500'),item('text','costCenter','costCenter',default='DEMO-01'),item('text','reference','reference',default='DEMO-ONLY')])]) ]}
  # Stable unique IDs for transparent wizard pages as well.
  for n, step in enumerate(design['items']): step['id'] = f'step_{n}'
  write(ROOT / f'data/formdesigns/{direction}-invoice-accounting.json', design)
  report_dir = ROOT / 'data/reports/invoices'; report_dir.mkdir(parents=True, exist_ok=True)
  (report_dir / f'{direction}-invoice.fo').write_text(FO, encoding='utf-8')

FO = '''<?xml version="1.0" encoding="UTF-8"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format" font-family="Helvetica" font-size="9pt" color="#203044">
 <fo:layout-master-set><fo:simple-page-master master-name="invoice" page-width="210mm" page-height="297mm" margin="18mm"><fo:region-body margin-top="8mm" margin-bottom="10mm"/><fo:region-after extent="7mm"/></fo:simple-page-master></fo:layout-master-set>
 <fo:page-sequence master-reference="invoice"><fo:static-content flow-name="xsl-region-after"><fo:block font-size="7pt" color="#63758a" border-top="0.5pt solid #d6dfe8" padding-top="3mm">{{Labels.demo}} · {{Company.email}}<fo:leader leader-pattern="space"/> <fo:page-number/></fo:block></fo:static-content>
 <fo:flow flow-name="xsl-region-body">
  <fo:block font-size="10pt" color="#2563a0" font-weight="bold">{{Company.name}}</fo:block>
  <fo:block font-size="25pt" font-weight="bold" space-before="5mm" space-after="3mm">{{Title}}</fo:block>
  <fo:block color="#63758a" space-after="9mm">{{Labels.number}}: {{Invoice.number}} · {{Labels.date}}: {{Invoice.date}} · {{Labels.dueDate}}: {{Invoice.dueDate}}</fo:block>
  <fo:block font-weight="bold" font-size="12pt">{{Party.company}}</fo:block><fo:block white-space-collapse="false" linefeed-treatment="preserve" space-before="2mm">{{Party.address}}</fo:block><fo:block space-before="2mm" space-after="8mm">{{Party.email}}</fo:block>
  <fo:table table-layout="fixed" width="100%" border-collapse="collapse"><fo:table-column column-width="12mm"/><fo:table-column column-width="60mm"/><fo:table-column column-width="17mm"/><fo:table-column column-width="27mm"/><fo:table-column column-width="19mm"/><fo:table-column column-width="39mm"/>
   <fo:table-header background-color="#eaf0f7"><fo:table-row font-weight="bold"><fo:table-cell padding="2mm"><fo:block>{{Labels.position}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block>{{Labels.description}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block>{{Labels.quantity}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block>{{Labels.unitPrice}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block>{{Labels.vatRate}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block text-align="end">{{Labels.net}}</fo:block></fo:table-cell></fo:table-row></fo:table-header>
   <fo:table-body>{{#each Lines}}<fo:table-row border-bottom="0.5pt solid #d6dfe8"><fo:table-cell padding="2mm"><fo:block>{{position}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block>{{description}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block>{{quantity}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block>{{unitPrice}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block>{{vatRate}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block text-align="end">{{net}}</fo:block></fo:table-cell></fo:table-row>{{/each}}</fo:table-body>
  </fo:table>
  <fo:block text-align="end" space-before="5mm">{{Labels.net}}: {{Summary.net}} {{Summary.currency}}</fo:block><fo:block text-align="end" space-before="2mm">{{Labels.tax}}: {{Summary.tax}} {{Summary.currency}}</fo:block><fo:block text-align="end" font-size="14pt" font-weight="bold" space-before="2mm" space-after="10mm">{{Labels.gross}}: {{Summary.gross}} {{Summary.currency}}</fo:block>
  <fo:block font-size="13pt" font-weight="bold" space-after="3mm" keep-with-next="always">{{Labels.accounting}}</fo:block><fo:block color="#63758a" space-after="3mm">{{Labels.postingDate}}: {{Accounting.postingDate}} · {{Labels.journal}}: {{Accounting.journal}} · {{Labels.reference}}: {{Accounting.reference}}</fo:block>
  <fo:table table-layout="fixed" width="100%"><fo:table-column column-width="22mm"/><fo:table-column column-width="65mm"/><fo:table-column column-width="29mm"/><fo:table-column column-width="29mm"/><fo:table-column column-width="29mm"/>
   <fo:table-header background-color="#eaf0f7"><fo:table-row font-weight="bold"><fo:table-cell padding="2mm"><fo:block>{{Labels.account}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block>{{Labels.description}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block>{{Labels.costCenter}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block text-align="end">{{Labels.debit}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block text-align="end">{{Labels.credit}}</fo:block></fo:table-cell></fo:table-row></fo:table-header>
   <fo:table-body>{{#each Journal}}<fo:table-row border-bottom="0.5pt solid #d6dfe8"><fo:table-cell padding="2mm"><fo:block>{{account}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block>{{description}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block>{{costCenter}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block text-align="end">{{debit}}</fo:block></fo:table-cell><fo:table-cell padding="2mm"><fo:block text-align="end">{{credit}}</fo:block></fo:table-cell></fo:table-row>{{/each}}</fo:table-body>
  </fo:table><fo:block text-align="end" font-weight="bold" space-before="3mm">{{Labels.debit}}: {{Summary.debit}} · {{Labels.credit}}: {{Summary.credit}} {{Summary.currency}}</fo:block>
  <fo:block space-before="8mm" color="#63758a">{{Form.notes}}</fo:block>
 </fo:flow></fo:page-sequence>
</fo:root>'''

if __name__ == '__main__':
 generate()
 print('Generated two fictional invoice forms, FOP reports and shared captions.')
