"""
Batch Post-Processor: Colors all domain files with omission (green) and reverse-scored (red) headers
"""
import sys
import io
from pathlib import Path

# Fix Windows console encoding
if sys.platform == 'win32':
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

BASE_DIR = Path(__file__).resolve().parent.parent
OUTPUT_DIR = BASE_DIR / "output" / "full_run"
MAPPING_FILE = BASE_DIR / "data" / "AllQuestions.xlsx"

# Import post_processor function
sys.path.insert(0, str(BASE_DIR / "scripts"))
from post_processor import post_process_file

def batch_post_process():
    """Post-process all domain files"""
    print("=" * 80)
    print("🎨 BATCH POST-PROCESSING: Coloring Headers")
    print("=" * 80)
    print()
    
    if not MAPPING_FILE.exists():
        print(f"❌ ERROR: Mapping file not found: {MAPPING_FILE}")
        return False
    
    # Domain files to process
    domain_files = {
        'adolescense': [
            'Personality_14-17.xlsx',
            'Grit_14-17.xlsx',
            'Emotional_Intelligence_14-17.xlsx',
            'Vocational_Interest_14-17.xlsx',
            'Learning_Strategies_14-17.xlsx'
        ],
        'adults': [
            'Personality_18-23.xlsx',
            'Grit_18-23.xlsx',
            'Emotional_Intelligence_18-23.xlsx',
            'Vocational_Interest_18-23.xlsx',
            'Learning_Strategies_18-23.xlsx'
        ]
    }
    
    total_files = 0
    processed_files = 0
    failed_files = []
    
    for age_group, files in domain_files.items():
        print(f"📂 Processing {age_group.upper()} files...")
        print("-" * 80)
        
        for file_name in files:
            total_files += 1
            file_path = OUTPUT_DIR / age_group / "5_domain" / file_name
            
            if not file_path.exists():
                print(f"  ⚠️ SKIP: {file_name} (file not found)")
                failed_files.append((file_name, "File not found"))
                continue
            
            try:
                print(f"  🎨 Processing: {file_name}")
                post_process_file(str(file_path), str(MAPPING_FILE))
                processed_files += 1
                print()
            except Exception as e:
                print(f"  ❌ ERROR processing {file_name}: {e}")
                failed_files.append((file_name, str(e)))
                print()
    
    print("=" * 80)
    print(f"✅ BATCH POST-PROCESSING COMPLETE")
    print(f"   Processed: {processed_files}/{total_files} files")
    if failed_files:
        print(f"   Failed: {len(failed_files)} files")
        for file_name, error in failed_files:
            print(f"      - {file_name}: {error}")
    print("=" * 80)
    
    return len(failed_files) == 0

if __name__ == "__main__":
    success = batch_post_process()
    sys.exit(0 if success else 1)
