
from database_setup import create_database
from models import db, User, Category, Job, Application, Contract, Payment, Invoice, WHSAssessment, Dispute, JobProgress, Review, AuditLog
from datetime import datetime, timedelta, date
import json

def test_chunk4():
    app = create_database()
    
    with app.app_context():
        print("🧪 Testing CHUNK 4: Safety Compliance & Trust Models...")
        
        # Clear existing data
        db.drop_all()
        db.create_all()
        
        # Create test users
        contractor = User(
            email='contractor@rateright.com.au',
            first_name='Emma',
            last_name='Taylor',
            role='contractor',
            phone_number='0412345678',
            location='Perth, WA',
            business_name='Taylor Construction',
            abn_number='12345678901',
            gst_registered=True
        )
        contractor.set_password('password123')
        db.session.add(contractor)
        
        worker = User(
            email='worker@rateright.com.au',
            first_name='Jake',
            last_name='Wilson',
            role='worker',
            phone_number='0423456789',
            location='Perth, WA',
            primary_trade='Steelfixer',
            abn_number='98765432109',
            gst_registered=True,
            public_liability_insurance='QBE-PL-2025-001',
            public_liability_amount=20000000.00,
            jobs_completed=28,
            average_rating=4.9,
            total_reviews=22
        )
        worker.set_password('password123')
        db.session.add(worker)
        
        # Create category and job
        category = Category(
            name='Steelfixer',
            description='Steel reinforcement and rebar work',
            whs_risk_level='high',
            insurance_requirements='$20M public liability required'
        )
        db.session.add(category)
        
        db.session.commit()
        
        job = Job(
            title='Steel Reinforcement - Basement',
            description='Steel fixing for basement construction. Complex rebar layout.',
            contractor_id=contractor.id,
            category_id=category.id,
            location='Perth, WA',
            budget_min=2000,
            budget_max=3000,
            whs_requirements='Manual handling training, cut-resistant gloves, site induction',
            insurance_required=True,
            white_card_required=True,
            status='in_progress'
        )
        db.session.add(job)
        
        db.session.commit()
        
        # Create application and contract
        application = Application(
            job_id=job.id,
            worker_id=worker.id,
            status='accepted',
            proposed_rate=2800,
            cover_letter='Qualified steelfixer, can read complex plans.',
            abn_verified=True,
            insurance_verified=True
        )
        db.session.add(application)
        
        db.session.commit()
        
        contract = Contract(
            job_id=job.id,
            application_id=application.id,
            contractor_id=contractor.id,
            worker_id=worker.id,
            agreed_rate=2800,
            start_date=date.today() - timedelta(days=5),
            expected_completion_date=date.today() + timedelta(days=10),
            terms_and_conditions='Standard ICA template with Fair Work compliance.',
            contractor_signed=True,
            worker_signed=True,
            status='signed'
        )
        db.session.add(contract)
        
        db.session.commit()
        
        # Create WHS Assessment
        whs_assessment = WHSAssessment(
            job_id=job.id,
            contract_id=contract.id,
            risk_assessment='High risk: Steel fixing. Controls: PPE, lifting aids, manual handling training.',
            safety_plan_accepted=True,
            incident_report='No incidents reported.',
            insurance_verified=True,
            completed_by=contractor.id
        )
        db.session.add(whs_assessment)
        
        # Create Job Progress
        job_progress = JobProgress(
            job_id=job.id,
            contract_id=contract.id,
            status='in_progress',
            start_date=date.today() - timedelta(days=5),
            progress_percentage=60,
            worker_notes='60% complete. Basement level 1 finished.',
            contractor_notes='Good progress, high quality work.',
            updated_by=worker.id
        )
        db.session.add(job_progress)
        
        # Create Review
        review = Review(
            reviewer_id=contractor.id,
            reviewee_id=worker.id,
            job_id=job.id,
            rating=5,
            comment='Outstanding steelfixing work. Highly recommend Jake for complex projects.'
        )
        db.session.add(review)
        
        # Create Test Dispute
        dispute = Dispute(
            job_id=job.id,
            complainant_id=worker.id,
            respondent_id=contractor.id,
            dispute_type='scope_change',
            description='Additional rebar work required due to structural changes.',
            evidence_urls='["/evidence/drawings_v2.pdf", "/evidence/photos_extra_work.jpg"]',
            status='investigating',
            dispute_resolution_method='mediation'
        )
        db.session.add(dispute)
        
        # Create Audit Log
        audit_log = AuditLog(
            table_name='contracts',
            record_id=contract.id,
            action='create',
            old_values='{}',
            new_values=json.dumps({"status": "signed", "agreed_rate": "2800"}),
            changed_by=contractor.id
        )
        db.session.add(audit_log)
        
        db.session.commit()
        
        # Verify counts
        user_count = User.query.count()
        job_count = Job.query.count()
        contract_count = Contract.query.count()
        whs_count = WHSAssessment.query.count()
        progress_count = JobProgress.query.count()
        review_count = Review.query.count()
        dispute_count = Dispute.query.count()
        audit_count = AuditLog.query.count()
        
        print(f"✅ Users created: {user_count}")
        print(f"✅ Jobs created: {job_count}")
        print(f"✅ Contracts created: {contract_count}")
        print(f"✅ WHS assessments: {whs_count}")
        print(f"✅ Job progress records: {progress_count}")
        print(f"✅ Reviews: {review_count}")
        print(f"✅ Disputes: {dispute_count}")
        print(f"✅ Audit logs: {audit_count}")
        
        # Test safety compliance workflow
        test_whs = WHSAssessment.query.first()
        test_progress = JobProgress.query.first()
        test_review = Review.query.first()
        test_dispute = Dispute.query.first()
        
        print(f"✅ WHS safety plan accepted: {test_whs.safety_plan_accepted}")
        print(f"✅ Insurance verified: {test_whs.insurance_verified}")
        print(f"✅ Job progress: {test_progress.progress_percentage}%")
        print(f"✅ Worker rating: {test_review.rating}/5 stars")
        print(f"✅ Dispute type: {test_dispute.dispute_type}")
        print(f"✅ Dispute status: {test_dispute.status}")
        
        # Test worker profile updates
        worker_profile = User.query.filter_by(role='worker').first()
        print(f"✅ Worker completed jobs: {worker_profile.jobs_completed}")
        print(f"✅ Worker average rating: {worker_profile.average_rating}")
        print(f"✅ Worker total reviews: {worker_profile.total_reviews}")
        
        print("✅ CHUNK 4 completed successfully!")
        print("✅ Safety workflow: WHS Assessment → Progress Tracking → Reviews")
        print("✅ WHS Act 2011 compliance ready!")
        print("✅ Trust system working (reviews + disputes)")
        print("✅ Audit trail for legal compliance!")
        print("📦 Ready for CHUNK 5...")

if __name__ == '__main__':
    test_chunk4()
"""Test Chunk 4: Contract Management and Payment System"""

def test_chunk4():
    """Test contract and payment models with legal compliance"""
    print("🧪 Testing Chunk 4: Contract Management + Payments")
    
    try:
        from app import create_app
        from app.models import Contract, Payment, Invoice, User, Job, Category, Application
        from app.extensions import db
        from app.utils.compliance import calculate_gst, generate_payment_reference
        from datetime import date, timedelta
        
        app = create_app()
        
        with app.app_context():
            # Create tables
            db.create_all()
            print("✅ Database tables created (contracts, payments, invoices)")
            
            # Test utilities
            gst = calculate_gst(1000)
            assert gst == 100.0
            print("✅ GST calculation works (10%)")
            
            payment_ref = generate_payment_reference()
            assert len(payment_ref) > 10
            print("✅ Payment reference generation works")
            
            # Create test data
            contractor = User(
                email='contractor@test.com',
                first_name='John',
                last_name='Contractor',
                role='contractor',
                phone_number='0412345678',
                location='Sydney, NSW',
                business_name='John\'s Construction',
                abn_number='12345678901',
                gst_registered=True
            )
            contractor.set_password('password123')
            db.session.add(contractor)
            
            worker = User(
                email='worker@test.com',
                first_name='Jane',
                last_name='Worker',
                role='worker',
                phone_number='0423456789',
                location='Sydney, NSW',
                primary_trade='Electrician',
                abn_number='98765432109',
                gst_registered=True
            )
            worker.set_password('password123')
            db.session.add(worker)
            
            category = Category(
                name='Electrical',
                description='Electrical work',
                whs_risk_level='high'
            )
            db.session.add(category)
            
            db.session.commit()
            
            job = Job(
                title='Electrical Installation',
                description='Install electrical systems',
                contractor_id=contractor.id,
                category_id=category.id,
                location='Sydney, NSW',
                budget_min=2000,
                budget_max=3000
            )
            db.session.add(job)
            
            application = Application(
                job_id=job.id,
                worker_id=worker.id,
                status='accepted',
                proposed_rate=2500
            )
            db.session.add(application)
            
            db.session.commit()
            
            # Test contract creation
            contract = Contract(
                job_id=job.id,
                contractor_id=contractor.id,
                worker_id=worker.id,
                agreed_rate=2500,
                start_date=date.today(),
                end_date=date.today() + timedelta(days=7),
                scope_of_work='Install electrical systems in new building'
            )
            db.session.add(contract)
            db.session.commit()
            
            print("✅ Contract created successfully")
            
            # Test payment creation
            payment = Payment(
                contract_id=contract.id,
                payment_reference=generate_payment_reference()
            )
            payment.calculate_amounts()
            db.session.add(payment)
            db.session.commit()
            
            print("✅ Payment created with calculated amounts")
            
            # Test invoice creation
            invoice = Invoice(
                payment_id=payment.id,
                description='Electrical installation services',
                due_date=date.today() + timedelta(days=30),
                amount_ex_gst=2500,
                gst_amount=250,
                total_amount=2750,
                supplier_abn=worker.abn_number,
                supplier_name=worker.business_name or f"{worker.first_name} {worker.last_name}",
                buyer_abn=contractor.abn_number,
                buyer_name=contractor.business_name
            )
            invoice.generate_invoice_number()
            db.session.add(invoice)
            db.session.commit()
            
            print("✅ Invoice created with GST compliance")
            
            # Test blueprint registration
            client = app.test_client()
            
            # Test legal endpoints
            response = client.post('/api/legal/validate-abn', 
                                  json={'abn': '12345678901'})
            assert response.status_code == 200
            print("✅ ABN validation endpoint works")
            
            # Test health check shows new models
            response = client.get('/api/health')
            data = response.get_json()
            assert 'Contract' in data['models']
            assert 'Payment' in data['models']
            assert 'Invoice' in data['models']
            print("✅ Health check shows contract/payment models")
            
            # Verify model counts
            contract_count = Contract.query.count()
            payment_count = Payment.query.count()
            invoice_count = Invoice.query.count()
            
            print(f"✅ Created {contract_count} contract(s)")
            print(f"✅ Created {payment_count} payment(s)")
            print(f"✅ Created {invoice_count} invoice(s)")
            
            print("\n🎉 CHUNK 4 COMPLETE!")
            print("📄 New models: Contract, Payment, Invoice")
            print("⚖️  Legal blueprint: /api/legal/*")
            print("🇦🇺 Australian compliance: Fair Work Act, GST, ABN")
            print("💰 Escrow payments with dispute protection")
            print("📊 GST-compliant invoicing system")
            
            return True
            
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    test_chunk4()
