#!/usr/bin/env python3
"""
Final Rating System Verification
Quick focused test to verify core rating functionality
"""

import pytest
from datetime import datetime, date, timedelta
from app import create_app
from app.extensions import db
from app.models import User, Contract, Job
from app.models.rating import Rating
from app.models.safety import Review
from app.models.category import Category
from app.services.rating_service import RatingService


def test_basic_rating_functionality():
    """Test basic rating system functionality works"""
    print("\n🔍 FINAL RATING VERIFICATION TEST")
    print("="*50)
    
    app = create_app()
    app.config.update({
        'TESTING': True,
        'SQLALCHEMY_DATABASE_URI': 'sqlite:///:memory:',
        'WTF_CSRF_ENABLED': False,
        'SECRET_KEY': 'test-secret-key'
    })
    
    with app.app_context():
        db.create_all()
        
        # Test 1: Create Rating object
        print("1. Testing Rating model creation...")
        try:
            rating = Rating()
            rating.quality_rating = 5
            rating.timeliness_rating = 4
            rating.communication_rating = 4
            rating.professionalism_rating = 5
            
            overall = rating.calculate_overall()
            expected = (5 + 4 + 4 + 5) / 4  # 4.5
            
            if abs(overall - expected) < 0.01:
                print("   ✅ Rating calculation works correctly")
            else:
                print(f"   ❌ Rating calculation failed: got {overall}, expected {expected}")
                
        except Exception as e:
            print(f"   ❌ Rating model error: {e}")
        
        # Test 2: Rating Service
        print("2. Testing Rating Service...")
        try:
            service = RatingService()
            
            # Test with non-existent user (should handle gracefully)
            avg = service.calculate_average_rating(99999)
            if avg == 0.0:
                print("   ✅ Service handles non-existent user correctly")
            else:
                print(f"   ❌ Service should return 0.0 for non-existent user, got {avg}")
                
        except Exception as e:
            print(f"   ❌ Rating service error: {e}")
        
        # Test 3: Contract Model Methods
        print("3. Testing Contract model methods...")
        try:
            contract = Contract()
            
            # Check if rating methods exist
            missing_methods = []
            expected_methods = [
                'is_mutual_rating_complete',
                'get_rating_status_for_user', 
                'get_pending_ratings_summary'
            ]
            
            for method in expected_methods:
                if not hasattr(contract, method):
                    missing_methods.append(method)
            
            if missing_methods:
                print(f"   ❌ Missing contract methods: {missing_methods}")
            else:
                print("   ✅ All contract rating methods exist")
                
        except Exception as e:
            print(f"   ❌ Contract model error: {e}")
        
        # Test 4: Database Schema Issues  
        print("4. Testing database schema issues...")
        try:
            # Test creating contract with long status
            contract = Contract(
                status='pending_completion_review'  # 25 characters
            )
            
            # In SQLite, this won't fail, but in production PostgreSQL it would
            if len(contract.status) > 20:
                print(f"   ⚠️  Status '{contract.status}' ({len(contract.status)} chars) may exceed VARCHAR(20)")
            else:
                print("   ✅ Status field length OK")
                
        except Exception as e:
            print(f"   ❌ Database schema error: {e}")
        
        # Test 5: Review Model Integration
        print("5. Testing Review model integration...")
        try:
            # Create a test user
            user = User(
                email='final_test@example.com',
                first_name='Final',
                last_name='Test',
                role='worker',
                phone_number='0400000099',
                is_active=True,
                privacy_consent=True,
                terms_accepted=True,
                terms_accepted_date=datetime.utcnow()
            )
            user.set_password('password123')
            db.session.add(user)
            db.session.flush()
            
            # Create a review
            review = Review(
                reviewer_id=1,
                reviewee_id=user.id,
                job_id=1,
                contract_id=1,
                overall_rating=4,
                quality_rating=4,
                communication_rating=3,
                safety_rating=5,
                comment='Test review'
            )
            db.session.add(review)
            db.session.commit()
            
            # Test service with real data
            service = RatingService()
            avg = service.calculate_average_rating(user.id)
            total = service.get_total_reviews(user.id)
            
            print(f"   ✅ User has {total} reviews with average {avg}")
            
        except Exception as e:
            print(f"   ❌ Review integration error: {e}")
        
        print("\n" + "="*50)
        print("FINAL VERIFICATION COMPLETE")
        print("="*50)


if __name__ == "__main__":
    test_basic_rating_functionality()
