#!/usr/bin/env python3
"""
Settings Loading Audit for Static HTML Modules

Scans all HTML modules to verify they properly load application settings.
Identifies modules that use currency formatting but don't have settings loading.
"""

import os
import re
from pathlib import Path

# Modules that have been verified/fixed
VERIFIED_MODULES = {
    'quotations.html': 'loadApplicationSettings() called in DOMContentLoaded ✅',
    'sales-reports.html': 'loadCurrencySettingsDirectly() called in DOMContentLoaded ✅',
    'ledgers.html': 'loadCurrencySettingsDirectly() added and called ✅',
    'accounting.html': 'loadCurrencySettingsDirectly() added and called ✅',
    'accounting-codes.html': 'window.settingsLoader.init() called in DOMContentLoaded ✅',
    'accounting-codes-dimensional.html': 'loadApplicationSettings() called in DOMContentLoaded ✅',
    'bank-accounts.html': 'BankAccountsApp loads appSettings in constructor ✅',
    'accounting-dimensions.html': 'No currency formatting needed ✅',
    'asset.html': 'loadCurrencySettingsDirectly() added and called ✅',
    'asset-management.html': 'loadSettings() called in DOMContentLoaded ✅',
    'bank-transactions.html': 'loadSettings() called in initializeData() + DOMContentLoaded ✅',
    'bank-reconciliations.html': 'loadSettings() called in initializeData() + DOMContentLoaded ✅',
    'dimensional-reports.html': 'loadSettings() + formatCurrency() working ✅',
    'purchase-orders.html': 'loadSettings() called in initializeData() + DOMContentLoaded ✅',
    'purchases.html': 'loadSettings() + formatCurrency() working ✅',
    'reports.html': 'loadSettings() + formatCurrency() working ✅',
    'vat-reports.html': 'loadSettings() + formatCurrency() working ✅',
    'vat-reconciliations.html': 'loadSettings() called in DOMContentLoaded ✅',
}

# Modules that need checking or may need fixes
# Additional modules to monitor for compliance
MODULES_TO_CHECK = [
    'bank-transfers.html',  # Has encoding error - low priority
    'billing.html',
    'inventory.html',
    'item-codes.html',
]

def check_file_for_settings_loading(filepath):
    """Check if a file loads application settings"""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()

            # Check for settings loading functions
            has_dom_content = 'DOMContentLoaded' in content
            has_load_settings = ('loadApplicationSettings' in content or
                               'loadCurrencySettings' in content or
                               'loadSettings' in content or
                               'settingsLoader' in content or
                               'appSettings' in content)
            has_currency_function = 'formatCurrency' in content or 'format currency' in content

            return {
                'has_dom_content': has_dom_content,
                'has_load_settings': has_load_settings,
                'has_currency_function': has_currency_function,
                'needs_attention': has_currency_function and not has_load_settings
            }
    except Exception as e:
        return {'error': str(e)}

def main():
    static_dir = Path('app/static')

    print("\n" + "="*80)
    print("SETTINGS LOADING AUDIT - STATIC HTML MODULES")
    print("="*80)

    print("\n✅ VERIFIED MODULES (Settings Loading Confirmed)")
    print("-" * 80)
    for module, status in sorted(VERIFIED_MODULES.items()):
        print(f"  {module:40} {status}")

    print("\n⚠️  MODULES REQUIRING ATTENTION")
    print("-" * 80)

    needs_fixes = []
    for module in MODULES_TO_CHECK:
        filepath = static_dir / module
        if filepath.exists():
            result = check_file_for_settings_loading(filepath)
            if result.get('error'):
                print(f"  ERROR: {module} - {result['error']}")
            elif result.get('needs_attention'):
                print(f"  ⚠️  {module:40} Has formatCurrency but no settings loading")
                needs_fixes.append(module)
            elif result.get('has_currency_function') and result.get('has_load_settings'):
                print(f"  ✓  {module:40} Has both currency function and settings loading")
            elif result.get('has_currency_function'):
                print(f"  ℹ️  {module:40} Has currency function, settings status unclear")

    print("\n📋 SUMMARY")
    print("-" * 80)
    print(f"  Verified modules: {len(VERIFIED_MODULES)}")
    print(f"  Modules needing fixes: {len(needs_fixes)}")

    if needs_fixes:
        print(f"\n  Modules to fix:")
        for module in needs_fixes:
            print(f"    - {module}")

    print("\n" + "="*80)
    print("KEY PATTERNS FOR SETTINGS LOADING")
    print("="*80)
    print("""
1. SIMPLE PATTERN (for modules that only need basic currency):

   async function loadCurrencySettingsDirectly() {
       try {
           const response = await fetch('/api/v1/settings');
           if (response.ok) {
               const data = await response.json();
               if (data.success && data.data) {
                   currentCurrency = data.data.currency || 'BWP';
                   currencySymbol = data.data.currency_symbol || 'P';
               }
           }
       } catch (error) {
           console.warn('[module] Error loading currency settings:', error);
       }
   }

   document.addEventListener('DOMContentLoaded', async function () {
       await loadCurrencySettingsDirectly();
       // ... rest of initialization
   });

2. FULL APPLICATION SETTINGS PATTERN (for complex modules):

   document.addEventListener('DOMContentLoaded', async function () {
       if (window.settingsLoader?.init) {
           await window.settingsLoader.init();
       }
       // ... rest of initialization
   });

3. CLASS-BASED PATTERN (for OOP modules):

   class MyApp {
       constructor() {
           this.appSettings = null;
           this.init();
       }

       async init() {
           try {
               await this.loadAppSettings();
               this.loadData();
           } catch (error) {
               console.error('Init failed:', error);
           }
       }

       async loadAppSettings() {
           const response = await fetch('/api/v1/settings');
           if (response.ok) {
               this.appSettings = await response.json();
           }
       }
   }

   document.addEventListener('DOMContentLoaded', () => {
       new MyApp();
   });
""")

    print("="*80 + "\n")

if __name__ == '__main__':
    main()
