#!/usr/bin/env python3
"""
Convert all INR (₹) fees to USD ($) across all PHP files.
Exchange rate: 1 USD = 84 INR
Round to nearest whole dollar.
Format: $XXX (no decimals, no commas for values < 10000)
"""

import re
import os
import sys

ROOT = '/Applications/XAMPP/xamppfiles/htdocs/aaa'
EXCHANGE_RATE = 84  # 1 USD = 84 INR

def inr_to_usd(inr_amount_str):
    """Convert INR string (e.g. '24,479') to USD rounded integer."""
    # Remove commas
    amount = int(inr_amount_str.replace(',', ''))
    usd = round(amount / EXCHANGE_RATE)
    return usd

def format_usd(amount):
    """Format USD amount with commas if >= 1000."""
    if amount >= 1000:
        return f"{amount:,}"
    return str(amount)

def convert_content(content):
    """Replace all ₹X,XXX patterns with $X,XXX in content."""
    
    # Pattern: ₹ followed by digits and commas (e.g. ₹24,479 or ₹1,904)
    pattern = re.compile(r'₹([\d,]+)')
    
    def replace_match(m):
        inr_str = m.group(1)
        usd = inr_to_usd(inr_str)
        return f"${format_usd(usd)}"
    
    new_content = pattern.sub(replace_match, content)
    return new_content

def process_files():
    """Walk all PHP files and convert INR to USD."""
    
    total_files = 0
    modified_files = 0
    
    for dirpath, dirnames, filenames in os.walk(ROOT):
        # Skip hidden dirs and cache dirs
        dirnames[:] = [d for d in dirnames if not d.startswith('.') and d not in ['assets', 'moengage', 'cdn-cgi', 'signals', 'infinity_images', '_data_image', '_next', '__website-next']]
        
        for filename in filenames:
            if not filename.endswith('.php'):
                continue
            
            filepath = os.path.join(dirpath, filename)
            
            try:
                with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
                    original = f.read()
            except Exception as e:
                print(f"ERROR reading {filepath}: {e}")
                continue
            
            # Check if file has any rupee symbols
            if '₹' not in original:
                continue
            
            total_files += 1
            
            # Convert
            modified = convert_content(original)
            
            if modified != original:
                # Count replacements
                orig_count = original.count('₹')
                new_count = modified.count('₹')
                replaced = orig_count - new_count
                
                try:
                    with open(filepath, 'w', encoding='utf-8') as f:
                        f.write(modified)
                    modified_files += 1
                    rel_path = os.path.relpath(filepath, ROOT)
                    print(f"✓ {rel_path} — {replaced} fee(s) converted")
                except Exception as e:
                    print(f"ERROR writing {filepath}: {e}")
            else:
                print(f"  (no change) {os.path.relpath(filepath, ROOT)}")
    
    print(f"\n{'='*60}")
    print(f"Total files with ₹: {total_files}")
    print(f"Files modified: {modified_files}")
    print("Done!")

if __name__ == '__main__':
    # Preview mode: show what conversions will happen
    if '--preview' in sys.argv:
        print("PREVIEW MODE - showing sample conversions:")
        sample_amounts = ['24,479', '17,135', '1,904', '45,000', '99,000', '1,20,000', '15,000', '8,500', '29,999']
        for a in sample_amounts:
            usd = inr_to_usd(a)
            print(f"  ₹{a} → ${format_usd(usd)}")
        print()
    
    process_files()
