
#!/usr/bin/env python3
"""
Debug Contract Creation Bug
Test contract creation with current application data
"""

from app import create_app
from app.models import Application, Contract, Job, User
from app.extensions import db
from datetime import datetime, date, timedelta

def test_contract_creation_bug():
    """Test contract creation with current application data"""
    
    print("🔧 TESTING CONTRACT CREATION BUG")
    print("=" * 50)
    
    app = create_app()
    
    with app.app_context():
        # Get the applications that have None proposed_rate
        applications = Application.query.filter_by(proposed_rate=None).all()
        
        if not applications:
            print("❌ No applications with None proposed_rate found")
            return
        
        application = applications[0]
        print(f"📋 Testing with Application ID: {application.id}")
        print(f"   Job: {application.job.title}")
        print(f"   Worker: {application.worker.first_name} {application.worker.last_name}")
        print(f"   proposed_rate: {application.proposed_rate}")
        print(f"   job.budget_max: {application.job.budget_max}")
        print(f"   job.hourly_rate: {application.job.hourly_rate}")
        
        # Test the logic manually
        proposed_rate = application.proposed_rate
        job_budget_max = application.job.budget_max
        job_hourly_rate = application.job.hourly_rate
        
        print(f"\n🧪 MANUAL LOGIC TEST:")
        if proposed_rate is not None:
            final_rate = float(proposed_rate)
            print(f"   Using proposed_rate: {final_rate}")
        else:
            print(f"   proposed_rate is None, checking fallbacks...")
            if job_budget_max is not None and float(job_budget_max) > 0:
                final_rate = float(job_budget_max)
                print(f"   Using job.budget_max: {final_rate}")
            elif job_hourly_rate is not None and float(job_hourly_rate) > 0:
                final_rate = float(job_hourly_rate)
                print(f"   Using job.hourly_rate: {final_rate}")
            else:
                final_rate = 5000.00
                print(f"   Using default rate: {final_rate}")
        
        print(f"🎯 Manual calculation result: {final_rate}")
        
        # Now test actual contract creation
        print(f"\n📄 TESTING ACTUAL CONTRACT CREATION:")
        
        # Delete any existing contracts for this application to avoid conflicts
        existing_contracts = Contract.query.filter_by(
            job_id=application.job_id,
            worker_id=application.worker_id
        ).all()
        
        for existing in existing_contracts:
            db.session.delete(existing)
        
        db.session.commit()
        
        # Create contract using same logic as in routes.py
        start_date = date.today()
        end_date = start_date + timedelta(days=30)
        
        contract = Contract(
            job_id=application.job_id,
            contractor_id=application.job.contractor_id,
            worker_id=application.worker_id,
            agreed_rate=final_rate,
            start_date=start_date,
            end_date=end_date,
            scope_of_work=application.job.description or "Contract work as per job posting",
            status='pending_agreement'
        )
        
        print(f"   Contract agreed_rate before save: {contract.agreed_rate}")
        print(f"   Contract agreed_rate type: {type(contract.agreed_rate)}")
        
        db.session.add(contract)
        db.session.commit()
        
        # Verify what was saved
        saved_contract = Contract.query.get(contract.id)
        print(f"   ✅ Contract saved with ID: {saved_contract.id}")
        print(f"   📊 Saved agreed_rate: {saved_contract.agreed_rate}")
        print(f"   📊 Saved agreed_rate type: {type(saved_contract.agreed_rate)}")
        
        if float(saved_contract.agreed_rate) == final_rate:
            print(f"   🎉 SUCCESS: Rate saved correctly!")
        else:
            print(f"   ❌ FAILURE: Rate mismatch!")
            print(f"      Expected: {final_rate}")
            print(f"      Got: {saved_contract.agreed_rate}")

if __name__ == "__main__":
    test_contract_creation_bug()
