"""
Debug test for E2E workflow
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app
from app.extensions import db
from app.models.user import User
from app.models.job import Job, Application
from app.models.category import Category
from app.models.contract import Contract
from datetime import datetime, timezone

def test_workflow():
    """Test the complete workflow step by step"""
    
    # Create app
    app = create_app()
    app.config['TESTING'] = True
    app.config['WTF_CSRF_ENABLED'] = False
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
    
    with app.app_context():
        # Setup database
        db.create_all()
        
        # Setup categories
        categories = [
            ('General Labor', 'General construction and labor work', 'low'),
            ('Renovation', 'Kitchen, bathroom, and home renovations', 'medium'),
            ('Electrical', 'Electrical installations and repairs', 'high'),
            ('Plumbing', 'Plumbing installations and repairs', 'high'),
            ('Carpentry', 'Carpentry and woodwork', 'medium')
        ]
        
        for name, desc, risk in categories:
            # Check if category already exists
            existing = Category.query.filter_by(name=name).first()
            if not existing:
                category = Category(
                    name=name,
                    description=desc,
                    whs_risk_level=risk,
                    white_card_required=True,
                    license_required=(risk == 'high')
                )
                db.session.add(category)
        db.session.commit()
        print("✓ Categories created")
        
        # Create test client
        client = app.test_client()
        
        # Step 1: Register Contractor
        print("\n=== STEP 1: REGISTER CONTRACTOR ===")
        contractor_data = {
            'first_name': 'Test',
            'last_name': 'Contractor',
            'email': 'contractor@example.com',
            'password': 'TestPass123!',
            'confirm_password': 'TestPass123!',
            'abn_number': '12345678901',
            'role': 'contractor',
            'phone_number': '0412345678',
            'location': 'Sydney'
        }
        
        response = client.post('/register', data=contractor_data, follow_redirects=True)
        print(f"Registration response code: {response.status_code}")
        
        # Check if contractor was created
        contractor = User.query.filter_by(email='contractor@example.com').first()
        if contractor:
            print(f"✓ Contractor created: {contractor.email}, ID: {contractor.id}")
        else:
            print("✗ Contractor not found in database")
            return
        
        # Clear session completely
        client.get('/logout')
        
        # Step 2: Register Worker
        print("\n=== STEP 2: REGISTER WORKER ===")
        worker_data = {
            'first_name': 'Test',
            'last_name': 'Worker',
            'email': 'worker@example.com',
            'password': 'TestPass123!',
            'confirm_password': 'TestPass123!',
            'abn_number': '98765432109',
            'role': 'worker',
            'phone_number': '0498765432',
            'location': 'Sydney'
        }
        
        response = client.post('/register', data=worker_data, follow_redirects=True)
        print(f"Registration response code: {response.status_code}")
        
        # Check if worker was created
        worker = User.query.filter_by(email='worker@example.com').first()
        if worker:
            print(f"✓ Worker created: {worker.email}, ID: {worker.id}")
        else:
            print("✗ Worker not found in database")
            return
        
        # Clear session again
        client.get('/logout')
        
        # Step 3: Login as Contractor
        print("\n=== STEP 3: LOGIN AS CONTRACTOR ===")
        response = client.post('/login', data={
            'email': 'contractor@example.com',
            'password': 'TestPass123!'
        }, follow_redirects=True)
        
        if b'Dashboard' in response.data or b'dashboard' in response.data:
            print("✓ Contractor logged in successfully")
        else:
            print("✗ Contractor login failed")
            print(f"Response contains: {response.data[:500]}")
        
        # Step 4: Post a Job
        print("\n=== STEP 4: POST JOB ===")
        job_data = {
            'title': 'Test Kitchen Renovation',
            'category_id': 2,  # Renovation category
            'location': 'Sydney, NSW',
            'hourly_rate': 50.00,
            'budget_min': 1000,
            'budget_max': 5000,
            'description': 'Complete kitchen renovation',
            'whs_requirements': 'White Card required',
            'white_card_required': 'on',
            'insurance_required': 'on'
        }
        
        response = client.post('/jobs/post', data=job_data, follow_redirects=True)
        print(f"Job post response code: {response.status_code}")
        
        # Check if job was created
        job = Job.query.filter_by(title='Test Kitchen Renovation').first()
        if job:
            print(f"✓ Job created: {job.title}, ID: {job.id}")
        else:
            print("✗ Job not found in database")
            return
        
        # Logout contractor
        response = client.get('/logout', follow_redirects=False)
        print(f"Logout response code: {response.status_code}")
        
        # Step 5: Login as Worker
        print("\n=== STEP 5: LOGIN AS WORKER ===")
        response = client.post('/login', data={
            'email': 'worker@example.com',
            'password': 'TestPass123!'
        }, follow_redirects=True)
        
        if b'Dashboard' in response.data or b'dashboard' in response.data:
            print("✓ Worker logged in successfully")
        else:
            print("✗ Worker login failed")
            # Check if user exists and password is correct
            worker = User.query.filter_by(email='worker@example.com').first()
            if worker:
                print(f"Worker exists: {worker.email}")
                if worker.check_password('TestPass123!'):
                    print("Password is correct")
                else:
                    print("Password is incorrect")
            else:
                print("Worker not found")
        
        # Step 6: Apply for Job
        print("\n=== STEP 6: APPLY FOR JOB ===")
        application_data = {
            'cover_letter': 'I have experience',
            'proposed_rate': 48.00
        }
        
        response = client.post(f'/jobs/{job.id}/apply', data=application_data, follow_redirects=True)
        print(f"Application response code: {response.status_code}")
        
        # Check if application was created
        application = Application.query.filter_by(job_id=job.id).first()
        if application:
            print(f"✓ Application created: ID {application.id}, Worker ID: {application.worker_id}")
        else:
            print("✗ Application not found in database")
            # Try to see all applications
            all_apps = Application.query.all()
            print(f"Total applications in database: {len(all_apps)}")
        
        # Logout worker
        client.get('/logout')
        
        # Step 7: Accept Application as Contractor
        print("\n=== STEP 7: ACCEPT APPLICATION ===")
        client.post('/login', data={
            'email': 'contractor@example.com',
            'password': 'TestPass123!'
        }, follow_redirects=True)
        
        if application:
            response = client.post(f'/applications/{application.id}/accept', follow_redirects=True)
            print(f"Accept response code: {response.status_code}")
            
            # Check if contract was created
            contract = Contract.query.filter_by(job_id=job.id).first()
            if contract:
                print(f"✓ Contract created: ID {contract.id}")
            else:
                print("✗ Contract not found")
        
        # Step 8: Sign Contract
        print("\n=== STEP 8: SIGN CONTRACT ===")
        if 'contract' in locals() and contract:
            # Contractor signs
            response = client.post(f'/contracts/{contract.id}/sign', follow_redirects=True)
            print(f"Contractor sign response: {response.status_code}")
            
            # Logout and login as worker
            client.get('/logout')
            client.post('/login', data={
                'email': 'worker@example.com',
                'password': 'TestPass123!'
            }, follow_redirects=True)
            
            # Worker signs
            response = client.post(f'/contracts/{contract.id}/sign', follow_redirects=True)
            print(f"Worker sign response: {response.status_code}")
            
            # Check contract status
            contract = Contract.query.get(contract.id)
            print(f"Contract status: {contract.status if contract else 'Not found'}")
        
        # Step 9: Complete and Rate
        print("\n=== STEP 9: COMPLETE AND RATE ===")
        if 'contract' in locals() and contract:
            # Mark as complete (worker)
            response = client.post(f'/contracts/{contract.id}/mark-complete', follow_redirects=True)
            print(f"Mark complete response: {response.status_code}")
            
            # Login as contractor and approve
            client.get('/logout')
            client.post('/login', data={
                'email': 'contractor@example.com',
                'password': 'TestPass123!'
            }, follow_redirects=True)
            
            response = client.post(f'/contracts/{contract.id}/approve-completion', follow_redirects=True)
            print(f"Approve completion response: {response.status_code}")
            
            # Check final contract status
            contract = Contract.query.get(contract.id)
            print(f"Final contract status: {contract.status if contract else 'Not found'}")
            
            # Navigate to closeout
            response = client.get(f'/contracts/{contract.id}/closeout')
            print(f"Closeout page response: {response.status_code}")
            
            # Rate as contractor
            rating_data = {
                'overall_rating': 5,
                'quality_rating': 5,
                'communication_rating': 5,
                'safety_rating': 5,
                'comment': 'Great work!',
                'would_work_again': 'on'
            }
            
            response = client.post(f'/contracts/{contract.id}/rate', data=rating_data, follow_redirects=True)
            print(f"Contractor rating response: {response.status_code}")
            
            # Rate as worker
            client.get('/logout')
            client.post('/login', data={
                'email': 'worker@example.com',
                'password': 'TestPass123!'
            }, follow_redirects=True)
            
            response = client.post(f'/contracts/{contract.id}/rate', data=rating_data, follow_redirects=True)
            print(f"Worker rating response: {response.status_code}")
            
            # Check final status
            contract = Contract.query.get(contract.id)
            print(f"Contract after ratings: {contract.status if contract else 'Not found'}")
        
        print("\n=== WORKFLOW COMPLETE ===")
        
        # Summary
        print("\n=== SUMMARY ===")
        users = User.query.all()
        jobs = Job.query.all()
        applications = Application.query.all()
        contracts = Contract.query.all()
        
        print(f"Users created: {len(users)}")
        print(f"Jobs created: {len(jobs)}")
        print(f"Applications created: {len(applications)}")
        print(f"Contracts created: {len(contracts)}")

if __name__ == "__main__":
    test_workflow()
