import os
from django.conf import settings
from django.shortcuts import render
from .models import OpenAIDiagnose
from django.http import JsonResponse

def dia_report(request, report_id):
    obj = OpenAIDiagnose.objects.get(id=report_id)
    file_path = os.path.join(settings.BASE_DIR, 'upload_file', obj.user.username, obj.uuid + '.md')
    print(file_path)
    if os.path.exists(file_path):
        with open(file_path, 'r', encoding='utf-8' ) as f:
            content = f.read()
        f.close()
    else:
        content = 'None'
    if obj:
        return render(request, 'dia_report.html', {'obj': obj, 'md_content': content, 'report_id': report_id})
    else:
        return render(request, 'dia_report.html', {'error': 'Report not found'})

def dia_report_update(request, report_id):
    if request.method == 'POST':
        obj = OpenAIDiagnose.objects.get(id=report_id)
        file_path = os.path.join(settings.BASE_DIR, 'upload_file', obj.user.username, obj.uuid + '.md')
        
        print(file_path)
        
        if os.path.exists(file_path):
            f = open(file_path, 'w', encoding='utf-8' )
            f.write(request.POST['md_new_content'])
            f.close()
        
        return JsonResponse({'message':"ok"}, status=200)