"""
Picture management routes
"""

import os
from datetime import datetime
from flask import Blueprint, render_template, request, redirect, url_for, flash, send_from_directory, make_response, jsonify, current_app
from werkzeug.utils import secure_filename

from app.models.database import PetPicture
from app.utils.auth import login_required
from app.utils.helpers import allowed_file, handle_like_action

pictures_bp = Blueprint('pictures', __name__)


@pictures_bp.route('/upload', methods=['GET', 'POST'])
@login_required
def upload():
    """Upload new pet picture"""
    if request.method == 'POST':
        if 'picture' not in request.files:
            flash('No file selected')
            return redirect(request.url)

        file = request.files['picture']
        subscriber_name = request.form.get('subscriber_name')
        description = request.form.get('description', '').strip()

        if file.filename == '':
            flash('No file selected')
            return redirect(request.url)

        if not subscriber_name:
            flash('Subscriber name is required')
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S_')
            filename = timestamp + filename
            
            # Ensure upload directory exists
            upload_path = current_app.config['UPLOAD_FOLDER']
            os.makedirs(upload_path, exist_ok=True)
            
            file.save(os.path.join(upload_path, filename))

            # Save to database
            PetPicture.create(filename, subscriber_name, description, datetime.now())

            flash('Picture uploaded successfully!')
            return redirect(url_for('main.index'))

        flash('Invalid file type')
        return redirect(request.url)

    return render_template('upload.html')


@pictures_bp.route('/mark_posted/<int:picture_id>', methods=['POST'])
@login_required
def mark_posted(picture_id):
    """Mark picture as posted"""
    PetPicture.mark_as_posted(picture_id)
    flash('Picture marked as posted!')
    return redirect(url_for('main.index'))


@pictures_bp.route('/like/<int:picture_id>', methods=['POST'])
def like_picture(picture_id):
    """Handle like/unlike actions"""
    return handle_like_action(picture_id, request)


@pictures_bp.route('/download/<filename>')
def download_file(filename):
    """Download original picture file"""
    return send_from_directory(
        current_app.config['UPLOAD_FOLDER'], filename, as_attachment=True
    )