
#!/usr/bin/env python3
"""
Create comprehensive test data for RateRight
"""

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

def create_test_data():
    """Create comprehensive test data for RateRight"""
    
    app = create_app()
    with app.app_context():
        print("🏗️  Creating RateRight Test Data")
        print("=" * 40)
        
        # Clear existing test data
        print("🧹 Clearing existing test data...")
        Contract.query.delete()
        Application.query.delete()
        Job.query.delete()
        db.session.commit()
        
        # Get existing users
        contractor = User.query.filter_by(email='contractor@test.com').first()
        worker = User.query.filter_by(email='worker@test.com').first()
        
        if not contractor or not worker:
            print("❌ Users not found! Run database_setup.py first")
            return
            
        # Get or create category
        category = Category.query.first()
        if not category:
            category = Category(name='General Construction', whs_risk_level='medium')
            db.session.add(category)
            db.session.commit()
        
        # 1. Create 5 test JOBS
        jobs_data = [
            {"title": "Kitchen Renovation", "budget": 2000, "location": "Sydney"},
            {"title": "Bathroom Tiling", "budget": 1500, "location": "Bondi"},
            {"title": "Deck Construction", "budget": 800, "location": "Manly"},
            {"title": "Fence Repair", "budget": 400, "location": "Surry Hills"},
            {"title": "Plumbing Fix", "budget": 300, "location": "Pyrmont"}
        ]
        
        jobs = []
        for job_data in jobs_data:
            job = Job(
                title=job_data["title"],
                description=f"Quality {job_data['title'].lower()} work needed. Professional tradesperson required.",
                contractor_id=contractor.id,
                category_id=category.id,
                location=job_data["location"],
                budget_min=job_data["budget"] * 0.8,
                budget_max=job_data["budget"],
                status='open',
                date_posted=datetime.utcnow(),
                insurance_required=True,
                white_card_required=True
            )
            db.session.add(job)
            jobs.append(job)
        
        db.session.commit()
        print(f"✅ Created {len(jobs)} jobs")
        
        # 2. Create test APPLICATIONS
        # Rocky applies to Kitchen and Deck jobs
        applications = []
        
        # Application 1: Kitchen Renovation
        app1 = Application(
            job_id=jobs[0].id,  # Kitchen Renovation
            worker_id=worker.id,
            status='pending',
            proposed_rate=1800,
            cover_letter="I have 10+ years experience in kitchen renovations. Professional work guaranteed.",
            date_applied=datetime.utcnow(),
            abn_verified=True,
            insurance_verified=True
        )
        db.session.add(app1)
        applications.append(app1)
        
        # Application 2: Deck Construction
        app2 = Application(
            job_id=jobs[2].id,  # Deck Construction
            worker_id=worker.id,
            status='pending',
            proposed_rate=750,
            cover_letter="Experienced deck builder. Can start immediately.",
            date_applied=datetime.utcnow(),
            abn_verified=True,
            insurance_verified=True
        )
        db.session.add(app2)
        applications.append(app2)
        
        db.session.commit()
        print(f"✅ Created {len(applications)} applications")
        
        # 3. Create 4 test CONTRACTS in different states
        contracts = []
        
        # Contract 1: Active - ready for worker to mark complete
        contract1 = Contract(
            job_id=jobs[1].id,  # Bathroom Tiling
            contractor_id=contractor.id,
            worker_id=worker.id,
            agreed_rate=650,
            rate_type='total',
            start_date=date.today() - timedelta(days=5),
            end_date=date.today() + timedelta(days=2),
            scope_of_work="Complete bathroom tiling including waterproofing and grouting",
            status='active',
            contractor_signed=True,
            worker_signed=True,
            contractor_signed_date=datetime.utcnow() - timedelta(days=5),
            worker_signed_date=datetime.utcnow() - timedelta(days=4),
            completion_status='in_progress',
            payment_status='pending'
        )
        db.session.add(contract1)
        contracts.append(contract1)
        
        # Contract 2: pending_review - worker marked complete, needs contractor approval
        contract2 = Contract(
            job_id=jobs[3].id,  # Fence Repair
            contractor_id=contractor.id,
            worker_id=worker.id,
            agreed_rate=850,
            rate_type='total',
            start_date=date.today() - timedelta(days=10),
            end_date=date.today() - timedelta(days=1),
            scope_of_work="Repair and reinforce fence panels, replace damaged posts",
            status='pending_review',
            contractor_signed=True,
            worker_signed=True,
            contractor_signed_date=datetime.utcnow() - timedelta(days=10),
            worker_signed_date=datetime.utcnow() - timedelta(days=9),
            completion_status='worker_completed',
            payment_status='pending',
            worker_completion_date=datetime.utcnow() - timedelta(days=1)
        )
        db.session.add(contract2)
        contracts.append(contract2)
        
        # Contract 3: pending_rating - both approved, ready for ratings
        contract3 = Contract(
            job_id=jobs[4].id,  # Plumbing Fix
            contractor_id=contractor.id,
            worker_id=worker.id,
            agreed_rate=1150,
            rate_type='total',
            start_date=date.today() - timedelta(days=15),
            end_date=date.today() - timedelta(days=3),
            scope_of_work="Fix kitchen plumbing leak and replace damaged pipes",
            status='pending_rating',
            contractor_signed=True,
            worker_signed=True,
            contractor_signed_date=datetime.utcnow() - timedelta(days=15),
            worker_signed_date=datetime.utcnow() - timedelta(days=14),
            completion_status='completed',
            payment_status='pending',
            worker_completion_date=datetime.utcnow() - timedelta(days=3),
            contractor_approval_date=datetime.utcnow() - timedelta(days=2),
            contractor_rated=False,
            worker_rated=False
        )
        db.session.add(contract3)
        contracts.append(contract3)
        
        # Contract 4: completed - fully done with ratings
        # Create a dummy job for this contract
        dummy_job = Job(
            title="Garden Landscaping",
            description="Professional garden landscaping completed",
            contractor_id=contractor.id,
            category_id=category.id,
            location="Paddington",
            budget_min=900,
            budget_max=950,
            status='closed',
            date_posted=datetime.utcnow() - timedelta(days=20)
        )
        db.session.add(dummy_job)
        db.session.commit()  # Commit to get the job ID
        
        contract4 = Contract(
            job_id=dummy_job.id,
            contractor_id=contractor.id,
            worker_id=worker.id,
            agreed_rate=950,
            rate_type='total',
            start_date=date.today() - timedelta(days=20),
            end_date=date.today() - timedelta(days=10),
            scope_of_work="Complete garden landscaping with new plants and irrigation",
            status='completed',
            contractor_signed=True,
            worker_signed=True,
            contractor_signed_date=datetime.utcnow() - timedelta(days=20),
            worker_signed_date=datetime.utcnow() - timedelta(days=19),
            completion_status='completed',
            payment_status='completed',
            worker_completion_date=datetime.utcnow() - timedelta(days=10),
            contractor_approval_date=datetime.utcnow() - timedelta(days=9),
            contractor_rated=True,
            worker_rated=True,
            mutual_rating_completed_date=datetime.utcnow() - timedelta(days=8)
        )
        db.session.add(contract4)
        contracts.append(contract4)
        
        db.session.commit()
        print(f"✅ Created {len(contracts)} contracts")
        
        # Summary
        print("\n🎉 Test data created successfully!")
        print("=" * 40)
        print("📊 SUMMARY:")
        print(f"   • {len(jobs)} jobs available")
        print(f"   • {len(applications)} pending applications")
        print(f"   • {len(contracts)} contracts in various states:")
        print(f"     - 1 active (ready for completion)")
        print(f"     - 1 pending review (awaiting contractor approval)")
        print(f"     - 1 pending rating (ready for mutual ratings)")
        print(f"     - 1 completed (fully finished)")
        print("\n🔑 LOGIN CREDENTIALS:")
        print("   Worker: worker@test.com")
        print("   Contractor: contractor@test.com")
        print("   Password: test123")
        print("\n💡 TIP: Login as worker to see contracts needing attention!")

if __name__ == "__main__":
    create_test_data()
