from flask import Blueprint, request, jsonify, session
from models.user_email import User, db
from models.inspection import Inspection
from models.room import Room
import json

rooms_bp = Blueprint('rooms', __name__)

# Simplified Room type templates with basic and optional professional items
ROOM_TEMPLATES = {
    'Living Room / Family Room': {
        'basic': [
            'Check flooring for damage, stains, or wear patterns',
            'Inspect windows for proper operation and locks',
            'Test all light switches and outlets',
            'Examine ceiling for cracks or water stains',
            'Test HVAC vents for airflow',
            'Check walls for cracks, holes, or paint issues',
            'Inspect baseboards and trim for damage'
        ],
        'professional': [
            'Test fireplace operation and safety features (if present)',
            'Check for adequate electrical capacity',
            'Verify smoke detector functionality and compliance'
        ]
    },
    'Kitchen': {
        'basic': [
            'Inspect countertops for damage or stains',
            'Test all appliances (stove, oven, microwave, dishwasher)',
            'Check plumbing under sink for leaks',
            'Test outlets and switches',
            'Check cabinet doors and drawers',
            'Test faucet operation and water pressure',
            'Examine flooring for water damage or wear'
        ],
        'professional': [
            'Test GFCI outlets and verify proper electrical connections',
            'Verify vent hood operation and filter condition',
            'Check backsplash for loose tiles or grout issues',
            'Verify adequate lighting over work areas',
            'Check for proper ventilation and exhaust'
        ]
    },
    'Primary Bathroom': {
        'basic': [
            'Inspect sinks, tub, and shower for leaks or damage',
            'Test water pressure and drainage',
            'Check caulking and grout condition',
            'Test exhaust fan operation',
            'Inspect toilet for proper function',
            'Check bathroom flooring for water damage',
            'Test lighting fixtures'
        ],
        'professional': [
            'Test GFCI outlets and electrical safety',
            'Check shower doors or curtain hardware',
            'Verify proper ventilation to prevent moisture buildup',
            'Test hot water temperature and recovery time',
            'Inspect mirrors and medicine cabinet mounting'
        ]
    },
    'Primary Bedroom': {
        'basic': [
            'Check flooring and baseboards for damage',
            'Inspect closet doors and shelves',
            'Test windows for proper operation and locks',
            'Test light fixtures and outlets',
            'Check ceiling for cracks or water stains',
            'Inspect walls for damage or paint issues',
            'Test HVAC vents for airflow'
        ],
        'professional': [
            'Check door operation and hardware',
            'Verify adequate electrical outlets for modern needs',
            'Inspect any built-in furniture or features'
        ]
    },
    'Secondary Bedroom': {
        'basic': [
            'Check flooring and baseboards for damage',
            'Inspect closet doors and shelves',
            'Test windows for proper operation and locks',
            'Test light fixtures and outlets',
            'Check ceiling for cracks or water stains',
            'Inspect walls for damage or paint issues',
            'Test HVAC vents for airflow'
        ],
        'professional': [
            'Check door operation and hardware',
            'Verify smoke detector functionality'
        ]
    },
    'Guest Bathroom / Hall Bathroom': {
        'basic': [
            'Test all plumbing fixtures for leaks',
            'Check water pressure and drainage',
            'Inspect caulking and grout condition',
            'Test exhaust fan operation',
            'Check flooring for water damage',
            'Test lighting'
        ],
        'professional': [
            'Test GFCI outlets and electrical safety',
            'Inspect vanity and storage areas',
            'Verify proper ventilation'
        ]
    },
    'Laundry Room / Utility Room': {
        'basic': [
            'Inspect washer and dryer connections',
            'Check for exhaust vent cleanliness',
            'Test utility sink plumbing (if present)',
            'Check floor for water damage',
            'Test lighting and outlets',
            'Check for adequate space and accessibility'
        ],
        'professional': [
            'Inspect electrical outlets and 220V connections',
            'Inspect any storage cabinets or shelving',
            'Verify proper venting to exterior',
            'Check for gas line connections (if applicable)'
        ]
    },
    'Garage': {
        'basic': [
            'Test garage door opener operation',
            'Check garage door balance and tracks',
            'Inspect electrical outlets and lighting',
            'Check walls and ceiling for damage',
            'Look for signs of pests',
            'Inspect concrete floor for cracks',
            'Test any windows for operation'
        ],
        'professional': [
            'Check garage door safety features',
            'Check for proper ventilation',
            'Verify adequate electrical capacity for modern needs',
            'Check weatherstripping and door seals',
            'Inspect any utility connections (water, gas)'
        ]
    },
    'Entry / Foyer': {
        'basic': [
            'Check flooring condition',
            'Test lighting fixtures and switches',
            'Inspect front door operation and locks',
            'Check walls and ceiling for damage',
            'Test any electrical outlets'
        ],
        'professional': [
            'Check door weatherstripping',
            'Inspect coat closet (if present)',
            'Verify proper ventilation'
        ]
    },
    'Dining Room': {
        'basic': [
            'Check flooring condition',
            'Test lighting fixtures',
            'Inspect windows',
            'Check walls and ceiling condition',
            'Test electrical outlets and switches',
            'Check HVAC vents for airflow'
        ],
        'professional': [
            'Test chandelier mounting security (if present)',
            'Inspect any built-in features'
        ]
    },
    'Hallways': {
        'basic': [
            'Check flooring and transitions between rooms',
            'Test lighting and switches',
            'Inspect walls for damage or scuff marks',
            'Check ceiling condition',
            'Test any electrical outlets'
        ],
        'professional': [
            'Inspect linen closets or storage areas',
            'Verify smoke detector placement and function'
        ]
    },
    'Closets': {
        'basic': [
            'Check door operation',
            'Inspect shelving and hanging rod security',
            'Test lighting (if present)',
            'Inspect flooring condition',
            'Check walls and ceiling for damage'
        ],
        'professional': [
            'Check for adequate ventilation',
            'Verify adequate space and organization'
        ]
    },
    'Front Yard / Porch': {
        'basic': [
            'Inspect porch structure and railings',
            'Check steps for stability',
            'Test exterior lighting',
            'Inspect landscaping and drainage',
            'Check walkways for cracks or trip hazards',
            'Check mailbox and address visibility'
        ],
        'professional': [
            'Check steps for proper rise/run ratios',
            'Test electrical outlets',
            'Inspect porch ceiling and overhang condition',
            'Check for proper grading away from foundation',
            'Verify adequate lighting for safety codes'
        ]
    },
    'Backyard / Patio': {
        'basic': [
            'Inspect fencing condition and gate operation',
            'Check patio/deck surface for cracks or wear',
            'Test exterior lighting',
            'Look for drainage issues',
            'Inspect any outdoor structures',
            'Check sprinkler system operation (if present)',
            'Inspect landscaping and tree condition'
        ],
        'professional': [
            'Test electrical outlets',
            'Check for privacy and security features',
            'Test any outdoor electrical or gas connections',
            'Verify adequate lighting for safety and security'
        ]
    },
    'Driveway': {
        'basic': [
            'Inspect surface for cracks or potholes',
            'Check drainage and water runoff',
            'Look for oil stains or surface deterioration',
            'Check for proper slope',
            'Verify adequate width'
        ],
        'professional': [
            'Inspect any retaining walls or borders',
            'Check for proper grading',
            'Verify adequate turning radius',
            'Inspect any lighting along driveway'
        ]
    },
    'Roof / Gutters': {
        'basic': [
            'Inspect roof surface for missing or damaged shingles',
            'Check gutters for proper attachment',
            'Look for signs of water damage or leaks',
            'Check downspouts for proper drainage',
            'Look for signs of pest intrusion'
        ],
        'professional': [
            'Inspect flashing around chimneys, vents, and penetrations',
            'Inspect attic ventilation (soffit and ridge vents)',
            'Check chimney condition and cap',
            'Inspect any skylights or roof penetrations',
            'Verify proper slope for water runoff'
        ]
    },
    'Pool': {
        'basic': [
            'Check water clarity and cleanliness',
            'Test pool pump and filter operation',
            'Inspect pool deck for cracks or wear',
            'Check skimmers and drains',
            'Inspect pool lighting',
            'Check for proper drainage around pool area'
        ],
        'professional': [
            'Verify safety barriers, gates, and fencing compliance',
            'Test any automated systems (cleaners, heaters)',
            'Inspect pool equipment and electrical connections',
            'Verify compliance with local safety codes',
            'Check for any structural issues or tile damage'
        ]
    },
    'Game Room / Media Room': {
        'basic': [
            'Check flooring condition',
            'Test electrical outlets',
            'Inspect lighting controls',
            'Check HVAC for comfort',
            'Test any built-in systems',
            'Inspect walls and ceiling condition'
        ],
        'professional': [
            'Check sound dampening',
            'Test electrical capacity for equipment',
            'Check HVAC adequacy for equipment heat load',
            'Verify proper electrical grounding for equipment'
        ]
    },
    'Office / Study': {
        'basic': [
            'Check electrical outlets',
            'Test lighting adequacy',
            'Inspect built-in desks or shelving',
            'Check HVAC comfort',
            'Inspect flooring and walls',
            'Check for adequate storage'
        ],
        'professional': [
            'Test internet connectivity',
            'Check HVAC noise levels',
            'Test any specialized electrical or data connections'
        ]
    },
    'Mudroom': {
        'basic': [
            'Check flooring durability',
            'Inspect storage solutions and hooks',
            'Test lighting and ventilation',
            'Check door operation'
        ],
        'professional': [
            'Check for proper drainage (if applicable)',
            'Inspect any utility connections',
            'Check door weatherstripping'
        ]
    },
    'Storage / Shed': {
        'basic': [
            'Inspect structure integrity',
            'Check roof condition',
            'Test door operation and security',
            'Look for pest intrusion signs',
            'Check for proper drainage around structure'
        ],
        'professional': [
            'Check electrical connections (if present)',
            'Inspect ventilation adequacy',
            'Check foundation condition'
        ]
    },
    'Attic': {
        'basic': [
            'Check insulation condition',
            'Look for signs of pest activity',
            'Check ventilation',
            'Look for water intrusion or roof leaks',
            'Check structural integrity'
        ],
        'professional': [
            'Inspect for air leaks and proper sealing',
            'Inspect electrical wiring and connections',
            'Inspect HVAC ductwork (if present)',
            'Check for proper vapor barriers'
        ]
    },
    'Basement': {
        'basic': [
            'Check for water intrusion or moisture',
            'Inspect foundation walls for cracks',
            'Look for signs of pest activity',
            'Check ventilation and air quality',
            'Check stairway safety and lighting'
        ],
        'professional': [
            'Test sump pump operation (if present)',
            'Check electrical systems and GFCI protection',
            'Inspect HVAC equipment and ductwork',
            'Inspect any finished areas'
        ]
    },
    'Fence / Gate': {
        'basic': [
            'Inspect fence posts for stability',
            'Check gate operation and latches',
            'Look for damaged or missing fence sections',
            'Check for proper height and privacy',
            'Check for adequate drainage under gates'
        ],
        'professional': [
            'Inspect any electrical gate operators',
            'Verify property line compliance',
            'Inspect fence materials for weather damage'
        ]
    },
    'Other': {
        'basic': [
            'Document unique features and conditions',
            'Inspect any specialized systems or equipment',
            'Test custom installations or modifications'
        ],
        'professional': [
            'Check compliance with local codes',
            'Note any unusual maintenance requirements',
            'Document any safety concerns or recommendations'
        ]
    }
}

@rooms_bp.route('/api/rooms/templates', methods=['GET'])
def get_room_templates():
    """Get available room types and their default checklist items"""
    if 'user_id' not in session:
        return jsonify({'error': 'Not authenticated'}), 401
    
    return jsonify({'templates': ROOM_TEMPLATES})

@rooms_bp.route('/api/inspections/<int:inspection_id>/rooms', methods=['GET'])
def get_inspection_rooms(inspection_id):
    """Get all rooms for a specific inspection"""
    if 'user_id' not in session:
        return jsonify({'error': 'Not authenticated'}), 401
    
    # Verify inspection belongs to user
    inspection = Inspection.query.filter_by(id=inspection_id, user_id=session['user_id']).first()
    if not inspection:
        return jsonify({'error': 'Inspection not found'}), 404
    
    rooms = Room.query.filter_by(inspection_id=inspection_id).all()
    return jsonify({'rooms': [room.to_dict() for room in rooms]})

@rooms_bp.route('/api/inspections/<int:inspection_id>/rooms', methods=['POST'])
def add_room_to_inspection(inspection_id):
    """Add a new room to an inspection"""
    if 'user_id' not in session:
        return jsonify({'error': 'Not authenticated'}), 401
    
    # Verify inspection belongs to user
    inspection = Inspection.query.filter_by(id=inspection_id, user_id=session['user_id']).first()
    if not inspection:
        return jsonify({'error': 'Inspection not found'}), 404
    
    data = request.get_json()
    room_type = data.get('room_type')
    
    if not room_type:
        return jsonify({'error': 'Room type is required'}), 400
    
    # Use room_type as room_name to avoid redundancy
    room_name = room_type
    
    # Get default checklist items for room type
    default_checklist = ROOM_TEMPLATES.get(room_type, {'basic': [], 'professional': []})
    
    room = Room(
        inspection_id=inspection_id,
        room_name=room_name,
        room_type=room_type,
        checklist_items=json.dumps(default_checklist)
    )
    
    db.session.add(room)
    db.session.commit()
    
    return jsonify({'room': room.to_dict()}), 201

@rooms_bp.route('/api/rooms/<int:room_id>', methods=['PUT'])
def update_room(room_id):
    """Update room inspection data"""
    if 'user_id' not in session:
        return jsonify({'error': 'Not authenticated'}), 401
    
    room = Room.query.get(room_id)
    if not room:
        return jsonify({'error': 'Room not found'}), 404
    
    # Verify room belongs to user's inspection
    inspection = Inspection.query.filter_by(id=room.inspection_id, user_id=session['user_id']).first()
    if not inspection:
        return jsonify({'error': 'Unauthorized'}), 403
    
    data = request.get_json()
    
    # Update room data
    for field in ['flooring_condition', 'flooring_notes', 'flooring_photos',
                  'windows_condition', 'windows_notes', 'windows_photos',
                  'electrical_condition', 'electrical_notes', 'electrical_photos',
                  'plumbing_condition', 'plumbing_notes', 'plumbing_photos',
                  'hvac_condition', 'hvac_notes', 'hvac_photos',
                  'walls_ceiling_condition', 'walls_ceiling_notes', 'walls_ceiling_photos',
                  'fixtures_condition', 'fixtures_notes', 'fixtures_photos',
                  'checklist_items', 'voice_memos', 'additional_notes']:
        if field in data:
            setattr(room, field, data[field])
    
    db.session.commit()
    
    return jsonify({'room': room.to_dict()})

@rooms_bp.route('/api/rooms/<int:room_id>', methods=['DELETE'])
def delete_room(room_id):
    """Delete a room from an inspection"""
    if 'user_id' not in session:
        return jsonify({'error': 'Not authenticated'}), 401
    
    room = Room.query.get(room_id)
    if not room:
        return jsonify({'error': 'Room not found'}), 404
    
    # Verify room belongs to user's inspection
    inspection = Inspection.query.filter_by(id=room.inspection_id, user_id=session['user_id']).first()
    if not inspection:
        return jsonify({'error': 'Unauthorized'}), 403
    
    db.session.delete(room)
    db.session.commit()
    
    return jsonify({'message': 'Room deleted successfully'})


@rooms_bp.route('/api/inspections/<int:inspection_id>/rooms/<int:room_id>', methods=['DELETE'])
def delete_room_from_inspection(inspection_id, room_id):
    """Delete a room from a specific inspection"""
    if 'user_id' not in session:
        return jsonify({'error': 'Not authenticated'}), 401
    
    # Verify inspection belongs to user
    inspection = Inspection.query.filter_by(id=inspection_id, user_id=session['user_id']).first()
    if not inspection:
        return jsonify({'error': 'Inspection not found'}), 404
    
    room = Room.query.filter_by(id=room_id, inspection_id=inspection_id).first()
    if not room:
        return jsonify({'error': 'Room not found'}), 404
    
    db.session.delete(room)
    db.session.commit()
    
    return jsonify({'message': 'Room deleted successfully'})

