from flask import Blueprint, jsonify, request, session
from src.models.user import Content, MediaFile, db
from src.routes.auth import login_required, admin_required
import os
from werkzeug.utils import secure_filename
import uuid

content_bp = Blueprint('content', __name__)

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'doc', 'docx'}
UPLOAD_FOLDER = 'uploads'

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@content_bp.route('/content', methods=['GET'])
def get_all_content():
    """Get all content items"""
    content_items = Content.query.all()
    return jsonify([item.to_dict() for item in content_items]), 200

@content_bp.route('/content/<section>', methods=['GET'])
def get_content_by_section(section):
    """Get content items by section"""
    content_items = Content.query.filter_by(section=section).all()
    return jsonify([item.to_dict() for item in content_items]), 200

@content_bp.route('/content/<section>/<key>', methods=['GET'])
def get_content_item(section, key):
    """Get specific content item"""
    content_item = Content.query.filter_by(section=section, key=key).first()
    if content_item:
        return jsonify(content_item.to_dict()), 200
    else:
        return jsonify({'error': 'Content not found'}), 404

@content_bp.route('/content', methods=['POST'])
@admin_required
def create_content():
    """Create new content item"""
    data = request.json
    section = data.get('section')
    key = data.get('key')
    value_en = data.get('value_en')
    value_he = data.get('value_he')
    content_type = data.get('content_type', 'text')
    
    if not section or not key:
        return jsonify({'error': 'Section and key are required'}), 400
    
    # Check if content already exists
    existing_content = Content.query.filter_by(section=section, key=key).first()
    if existing_content:
        return jsonify({'error': 'Content with this section and key already exists'}), 400
    
    content_item = Content(
        section=section,
        key=key,
        value_en=value_en,
        value_he=value_he,
        content_type=content_type,
        updated_by=session['user_id']
    )
    
    db.session.add(content_item)
    db.session.commit()
    
    return jsonify(content_item.to_dict()), 201

@content_bp.route('/content/<int:content_id>', methods=['PUT'])
@admin_required
def update_content(content_id):
    """Update existing content item"""
    content_item = Content.query.get_or_404(content_id)
    data = request.json
    
    if 'section' in data:
        content_item.section = data['section']
    if 'key' in data:
        content_item.key = data['key']
    if 'value_en' in data:
        content_item.value_en = data['value_en']
    if 'value_he' in data:
        content_item.value_he = data['value_he']
    if 'content_type' in data:
        content_item.content_type = data['content_type']
    
    content_item.updated_by = session['user_id']
    
    db.session.commit()
    
    return jsonify(content_item.to_dict()), 200

@content_bp.route('/content/<int:content_id>', methods=['DELETE'])
@admin_required
def delete_content(content_id):
    """Delete content item"""
    content_item = Content.query.get_or_404(content_id)
    db.session.delete(content_item)
    db.session.commit()
    
    return jsonify({'message': 'Content deleted successfully'}), 200

@content_bp.route('/content/bulk', methods=['POST'])
@admin_required
def bulk_update_content():
    """Bulk update multiple content items"""
    data = request.json
    content_updates = data.get('content', [])
    
    if not content_updates:
        return jsonify({'error': 'No content updates provided'}), 400
    
    updated_items = []
    
    for update in content_updates:
        section = update.get('section')
        key = update.get('key')
        value_en = update.get('value_en')
        value_he = update.get('value_he')
        content_type = update.get('content_type', 'text')
        
        if not section or not key:
            continue
        
        # Find existing content or create new
        content_item = Content.query.filter_by(section=section, key=key).first()
        
        if content_item:
            # Update existing
            content_item.value_en = value_en
            content_item.value_he = value_he
            content_item.content_type = content_type
            content_item.updated_by = session['user_id']
        else:
            # Create new
            content_item = Content(
                section=section,
                key=key,
                value_en=value_en,
                value_he=value_he,
                content_type=content_type,
                updated_by=session['user_id']
            )
            db.session.add(content_item)
        
        updated_items.append(content_item)
    
    db.session.commit()
    
    return jsonify({
        'message': f'Updated {len(updated_items)} content items',
        'items': [item.to_dict() for item in updated_items]
    }), 200

@content_bp.route('/media', methods=['GET'])
@login_required
def get_media_files():
    """Get all media files"""
    media_files = MediaFile.query.all()
    return jsonify([file.to_dict() for file in media_files]), 200

@content_bp.route('/media/upload', methods=['POST'])
@admin_required
def upload_media():
    """Upload media file"""
    if 'file' not in request.files:
        return jsonify({'error': 'No file provided'}), 400
    
    file = request.files['file']
    
    if file.filename == '':
        return jsonify({'error': 'No file selected'}), 400
    
    if file and allowed_file(file.filename):
        # Create upload directory if it doesn't exist
        upload_dir = os.path.join(os.path.dirname(__file__), '..', 'static', UPLOAD_FOLDER)
        os.makedirs(upload_dir, exist_ok=True)
        
        # Generate unique filename
        file_extension = file.filename.rsplit('.', 1)[1].lower()
        unique_filename = f"{uuid.uuid4().hex}.{file_extension}"
        
        file_path = os.path.join(upload_dir, unique_filename)
        file.save(file_path)
        
        # Save to database
        media_file = MediaFile(
            filename=unique_filename,
            original_filename=file.filename,
            file_path=f"/{UPLOAD_FOLDER}/{unique_filename}",
            file_type=file_extension,
            file_size=os.path.getsize(file_path),
            uploaded_by=session['user_id']
        )
        
        db.session.add(media_file)
        db.session.commit()
        
        return jsonify(media_file.to_dict()), 201
    
    return jsonify({'error': 'File type not allowed'}), 400

@content_bp.route('/media/<int:media_id>', methods=['DELETE'])
@admin_required
def delete_media(media_id):
    """Delete media file"""
    media_file = MediaFile.query.get_or_404(media_id)
    
    # Delete physical file
    file_path = os.path.join(os.path.dirname(__file__), '..', 'static', media_file.file_path.lstrip('/'))
    if os.path.exists(file_path):
        os.remove(file_path)
    
    # Delete from database
    db.session.delete(media_file)
    db.session.commit()
    
    return jsonify({'message': 'Media file deleted successfully'}), 200

@content_bp.route('/initialize-content', methods=['POST'])
@admin_required
def initialize_default_content():
    """Initialize default content for the website"""
    default_content = [
        # Hero section
        {'section': 'hero', 'key': 'title_he', 'value_en': 'Smart City Technologies', 'value_he': 'טכנולוגיות חכמות לעיר החכמה'},
        {'section': 'hero', 'key': 'subtitle_he', 'value_en': 'Managed by Artificial Intelligence', 'value_he': 'המנוהלות בבינה מלאכותית'},
        {'section': 'hero', 'key': 'description', 'value_en': 'Leading the future of urban infrastructure with advanced IoT solutions', 'value_he': 'מובילים את עתיד התשתיות העירוניות עם פתרונות IoT מתקדמים'},
        
        # Features section
        {'section': 'features', 'key': 'title', 'value_en': 'A complete software solution for you', 'value_he': 'פתרון תוכנה מקיף עבורכם'},
        {'section': 'features', 'key': 'description', 'value_en': 'Advanced smart city technologies with intelligent management capabilities', 'value_he': 'טכנולוגיות מתקדמות לעיר החכמה עם יכולות ניהול חכמות'},
        
        # Products
        {'section': 'products', 'key': 'ms4sc_title', 'value_en': 'MS4SC v1', 'value_he': 'MS4SC v1'},
        {'section': 'products', 'key': 'ms4sc_subtitle', 'value_en': 'Smart Meter Management System', 'value_he': 'מערכת ניהול מונים חכמים'},
        {'section': 'products', 'key': 'ms4sc_description', 'value_en': 'Comprehensive system for managing smart water and electricity prepaid meters for local authorities', 'value_he': 'מערכת מקיפה לניהול מונים חכמים של מים וחשמל בתשלום מראש עבור רשויות מקומיות'},
        
        {'section': 'products', 'key': 'geocheck_title', 'value_en': 'GeoCheck', 'value_he': 'GeoCheck'},
        {'section': 'products', 'key': 'geocheck_subtitle', 'value_en': 'Emergency Response Platform', 'value_he': 'פלטפורמת תגובה לחירום'},
        {'section': 'products', 'key': 'geocheck_description', 'value_en': 'Advanced platform for emergency alerts and citizen location communication for public safety', 'value_he': 'פלטפורמה מתקדמת להתרעות חירום ותקשורת מיקום אזרחים לבטיחות הציבור'},
        
        # Contact
        {'section': 'contact', 'key': 'title', 'value_en': 'Contact Us', 'value_he': 'צור קשר'},
        {'section': 'contact', 'key': 'description', 'value_en': 'Get in touch with us to learn more about our smart city solutions', 'value_he': 'צרו איתנו קשר כדי ללמוד עוד על פתרונות העיר החכמה שלנו'},
        {'section': 'contact', 'key': 'address', 'value_en': 'Jerusalem, Israel', 'value_he': 'ירושלים, ישראל'},
        {'section': 'contact', 'key': 'email', 'value_en': 'info@ms4sc.com', 'value_he': 'info@ms4sc.com'},
        {'section': 'contact', 'key': 'phone', 'value_en': '+972-XX-XXX-XXXX', 'value_he': '+972-XX-XXX-XXXX'},
    ]
    
    created_items = []
    
    for item_data in default_content:
        # Check if content already exists
        existing_content = Content.query.filter_by(
            section=item_data['section'], 
            key=item_data['key']
        ).first()
        
        if not existing_content:
            content_item = Content(
                section=item_data['section'],
                key=item_data['key'],
                value_en=item_data['value_en'],
                value_he=item_data['value_he'],
                content_type='text',
                updated_by=session['user_id']
            )
            db.session.add(content_item)
            created_items.append(content_item)
    
    db.session.commit()
    
    return jsonify({
        'message': f'Initialized {len(created_items)} content items',
        'items': [item.to_dict() for item in created_items]
    }), 200

