"""Radiology Images API routes."""
import os
import uuid
import base64
from werkzeug.utils import secure_filename
from flask import Blueprint, jsonify, request, current_app
from pydantic import ValidationError

from app.models.radiology_image import RadiologyImage
from app.repositories import radiology_image_repository
from app.routes.access import ensure_can_access_patient_data, ensure_can_create_for_patient
from app.routes.auth import auth_required

radiology_images_bp = Blueprint('radiology_images_api', __name__)

@radiology_images_bp.route('/images', methods=['POST'])
@auth_required
def create_radiology_image_endpoint():
    if request.is_json:
        payload = request.get_json(silent=True) or {}
    else:
        payload = request.form.to_dict()

    patient_id = str(payload.get('patientId', ''))
    create_err = ensure_can_create_for_patient(patient_id)
    if create_err:
        return create_err

    file = request.files.get('file')
    if file and file.filename != '':

        file_bytes = file.read()
        b64_str = base64.b64encode(file_bytes).decode('utf-8')
        mimetype = file.mimetype or 'image/png'
        payload['imageUrl'] = f"data:{mimetype};base64,{b64_str}"

    try:
        image = RadiologyImage.model_validate(payload)
    except ValidationError as exc:
        return jsonify({'error': 'ValidationError', 'detail': str(exc)}), 400

    created = radiology_image_repository.create(image)
    return jsonify(created.model_dump(by_alias=True, mode='json')), 201


@radiology_images_bp.route('/images/<image_id>', methods=['GET'])
@auth_required
def get_radiology_image_by_id_endpoint(image_id: str):
    image = radiology_image_repository.find_by_id(image_id)
    if not image:
        return jsonify({'error': 'NotFound'}), 404

    _, err = ensure_can_access_patient_data(str(image.patientId))
    if err:
        return err

    return jsonify(image.model_dump(by_alias=True, mode='json'))


@radiology_images_bp.route('/images', methods=['GET'])
@auth_required
def list_radiology_images_by_patient_endpoint():
    patient_id = request.args.get('patientId')
    if not patient_id:
        return jsonify({'error': 'MissingQueryParam', 'param': 'patientId'}), 400

    _, err = ensure_can_access_patient_data(patient_id)
    if err:
        return err

    images = radiology_image_repository.find_by_patient_id(patient_id)
    return jsonify([i.model_dump(by_alias=True, mode='json') for i in images])
