"""Test complete workflow: settings → baseline creation → verification."""
import os
import shutil
import tempfile
from pathlib import Path

print("Testing complete baseline workflow with zip_baselines setting")
print("=" * 70)
print()

# Create test project
temp_project = tempfile.mkdtemp(prefix="workflow_test_")

try:
    # Create some test files
    test_files = {
        "main.py": "# Main file\ndef main():\n    print('Hello')\n",
        "utils.py": "# Utilities\ndef helper():\n    return 42\n",
        "config.py": "# Configuration\nSETTING = 'value'\n"
    }
    
    for filename, content in test_files.items():
        (Path(temp_project) / filename).write_text(content, encoding='utf-8')
    
    print(f"✓ Test project created: {temp_project}")
    print(f"  Files: {len(test_files)}")
    print()
    
    from pyucc.core.differ import BaselineManager
    from pyucc.config import settings as app_settings
    
    baseline_dir = tempfile.mkdtemp(prefix="workflow_baselines_")
    
    # Scenario 1: Default settings (no zip)
    print("Scenario 1: Default settings (zip_baselines = False)")
    print("-" * 70)
    
    # Reset settings to default
    app_settings.save_settings({
        "baseline_dir": baseline_dir,
        "max_keep": 5,
        "zip_baselines": False
    })
    
    current_setting = app_settings.get_zip_baselines()
    print(f"  Current setting: zip_baselines = {current_setting}")
    
    bm1 = BaselineManager(temp_project, baselines_root=baseline_dir)
    baseline_1 = bm1.create_baseline_from_dir(
        temp_project,
        baseline_id="scenario_1_default",
        snapshot=True,
        compute_sha1=False
    )
    
    path_1 = bm1._baseline_dir(baseline_1)
    has_dir_1 = os.path.exists(os.path.join(path_1, "files"))
    has_zip_1 = os.path.exists(os.path.join(path_1, "files.zip"))
    
    print(f"  Baseline created: {baseline_1}")
    print(f"  Has files/ directory: {has_dir_1}")
    print(f"  Has files.zip: {has_zip_1}")
    
    if has_dir_1 and not has_zip_1:
        print("  ✅ Result: Fast mode (directory only)")
    else:
        print("  ❌ Result: Unexpected configuration!")
    print()
    
    # Scenario 2: Enable zip compression
    print("Scenario 2: Enable ZIP compression (zip_baselines = True)")
    print("-" * 70)
    
    app_settings.save_settings({
        "baseline_dir": baseline_dir,
        "max_keep": 5,
        "zip_baselines": True
    })
    
    current_setting = app_settings.get_zip_baselines()
    print(f"  Current setting: zip_baselines = {current_setting}")
    
    bm2 = BaselineManager(temp_project, baselines_root=baseline_dir)
    baseline_2 = bm2.create_baseline_from_dir(
        temp_project,
        baseline_id="scenario_2_with_zip",
        snapshot=True,
        compute_sha1=False
    )
    
    path_2 = bm2._baseline_dir(baseline_2)
    has_dir_2 = os.path.exists(os.path.join(path_2, "files"))
    has_zip_2 = os.path.exists(os.path.join(path_2, "files.zip"))
    
    print(f"  Baseline created: {baseline_2}")
    print(f"  Has files/ directory: {has_dir_2}")
    print(f"  Has files.zip: {has_zip_2}")
    
    if has_dir_2 and has_zip_2:
        # Compare sizes
        dir_size = sum(f.stat().st_size for f in Path(os.path.join(path_2, "files")).rglob('*') if f.is_file())
        zip_size = os.path.getsize(os.path.join(path_2, "files.zip"))
        compression_ratio = (1 - zip_size / dir_size) * 100 if dir_size > 0 else 0
        
        print(f"  Directory size: {dir_size} bytes")
        print(f"  ZIP size: {zip_size} bytes")
        print(f"  Compression: {compression_ratio:.1f}% space saved")
        print("  ✅ Result: Space-saving mode (directory + zip)")
    else:
        print("  ❌ Result: Unexpected configuration!")
    print()
    
    # Final summary
    print("=" * 70)
    print("SUMMARY")
    print("=" * 70)
    print()
    print("User Setting Options:")
    print("  • zip_baselines = False (default)")
    print("    - Creates only files/ directory")
    print("    - ⚡ Faster baseline creation")
    print("    - 💾 Uses more disk space")
    print("    - ✓ Recommended for most users")
    print()
    print("  • zip_baselines = True")
    print("    - Creates both files/ directory AND files.zip")
    print("    - 🐌 Slower baseline creation (compression)")
    print("    - 📦 Saves disk space (~30-70% compression)")
    print("    - ✓ Recommended for limited disk space")
    print()
    print("How to change:")
    print("  1. Click 'Settings...' button in the top bar")
    print("  2. Check/uncheck 'Create ZIP archives for baselines'")
    print("  3. Click 'Save'")
    print()
    
    success = has_dir_1 and not has_zip_1 and has_dir_2 and has_zip_2
    if success:
        print("🎉 ALL TESTS PASSED - Feature working correctly!")
    else:
        print("⚠️  Some tests failed")

finally:
    # Cleanup
    shutil.rmtree(temp_project, ignore_errors=True)
    if 'baseline_dir' in locals():
        shutil.rmtree(baseline_dir, ignore_errors=True)
