#!/usr/bin/env python3
"""
Master script to process all financial statements and generate CSV outputs
"""

import os
import subprocess
import sys
from datetime import datetime

def run_script(script_name, csv_output=False):
    """Run a processing script with optional CSV output"""
    cmd = [sys.executable, script_name]
    if csv_output:
        cmd.append('--csv')
    
    try:
        print(f"\n{'='*50}")
        print(f"Processing {script_name.replace('process_', '').replace('.py', '').replace('_', ' ').title()}...")
        print('='*50)
        subprocess.run(cmd, check=True)
        return True
    except subprocess.CalledProcessError as e:
        print(f"Error running {script_name}: {e}")
        return False

def main():
    import argparse
    
    parser = argparse.ArgumentParser(description='Process all financial statements')
    parser.add_argument('--csv', action='store_true', 
                       help='Output transaction data to CSV files')
    parser.add_argument('--bourso', action='store_true', 
                       help='Process only BoursoBank statements')
    parser.add_argument('--amex', action='store_true', 
                       help='Process only American Express statements')
    parser.add_argument('--monabanq', action='store_true', 
                       help='Process only Monabanq statements')
    parser.add_argument('--revolut', action='store_true', 
                       help='Process only Revolut statements')
    parser.add_argument('--sncf', action='store_true', 
                       help='Process only SNCF statements')
    parser.add_argument('--laposte', action='store_true', 
                       help='Process only La Poste statements')
    
    args = parser.parse_args()
    
    print(f"\n{'='*60}")
    print(f"Financial Statement Processor")
    print(f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"{'='*60}")
    
    scripts_to_run = []
    
    # Determine which scripts to run based on arguments
    if args.bourso or not any([args.bourso, args.amex, args.monabanq, args.revolut, args.sncf, args.laposte]):
        scripts_to_run.append('process_bourso.py')
    if args.amex or not any([args.bourso, args.amex, args.monabanq, args.revolut, args.sncf, args.laposte]):
        scripts_to_run.append('process_amex.py')
    if args.monabanq or not any([args.bourso, args.amex, args.monabanq, args.revolut, args.sncf, args.laposte]):
        scripts_to_run.append('process_monabanq.py')
    if args.revolut or not any([args.bourso, args.amex, args.monabanq, args.revolut, args.sncf, args.laposte]):
        scripts_to_run.append('process_expenses.py')
    if args.sncf or not any([args.bourso, args.amex, args.monabanq, args.revolut, args.sncf, args.laposte]):
        scripts_to_run.append('process_sncf.py')
    if args.laposte or not any([args.bourso, args.amex, args.monabanq, args.revolut, args.sncf, args.laposte]):
        scripts_to_run.append('process_laposte.py')
    
    # Run each script
    success_count = 0
    output_dir = '../output/csv'
    os.makedirs(output_dir, exist_ok=True)
    
    for script in scripts_to_run:
        if os.path.exists(script):
            # Pass CSV flag and output directory to all scripts
            if run_script(script, args.csv):
                success_count += 1
        else:
            print(f"Script not found: {script}")
    
    print(f"\n{'='*60}")
    print(f"Processing Complete: {success_count}/{len(scripts_to_run)} scripts executed successfully")
    if args.csv:
        print("CSV files have been generated for each directory")
    print(f"{'='*60}")

if __name__ == "__main__":
    main()