import os
import shutil
import threading
import subprocess
from datetime import datetime

from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required

from djangoProject import settings
from PAD_predict.models import PestDetectionRecord
from .models import DetectionFeedback
from app01.models import UserInfo

CLASS_MAP = {
    'Fruit Rot': 0, '果腐病': 0, '茄子绵疫病': 0, '绵疫病': 0, '免疫病': 0,
    'Fruit borer': 1, '蛀果虫': 1, '钻心虫': 1,
    'Healthy': 2, '健康': 2, '正常': 2,
    'Melon Thrips': 3, '瓜蓟马': 3, '蓟马': 3
}


def run_evolution_in_background():

    print("\n" + "🌟" * 20)
    print("【系统广播】经验池已满！紫睛灵正在后台启动自动演进...")

    project_root = settings.BASE_DIR
    evolve_script_path = os.path.join(project_root, 'yolo_evolve.py')

    try:
        process = subprocess.Popen(
            ['python', evolve_script_path],
            cwd=project_root,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )

        stdout, stderr = process.communicate()

        if process.returncode == 0:
            print("【系统广播】🎉 自动演进大功告成！新大脑已生成！")

            new_weight_path = os.path.join(project_root, 'runs', 'evolve', 'evolution_latest', 'weights', 'best.pt')

            old_weight_path = r"D:\eggplantshapeBS1\djangoProject\PAD_train\src\src\results\exp4\weights\best.pt"

            if os.path.exists(new_weight_path):
                shutil.copy2(new_weight_path, old_weight_path)
                print("【系统广播】🔄 权重文件已在后台自动物理替换完毕！")

            images_dir = os.path.join(settings.MEDIA_ROOT, 'evolve_dataset', 'images', 'train')
            labels_dir = os.path.join(settings.MEDIA_ROOT, 'evolve_dataset', 'labels', 'train')

            for filename in os.listdir(images_dir):
                os.remove(os.path.join(images_dir, filename))
            for filename in os.listdir(labels_dir):
                os.remove(os.path.join(labels_dir, filename))

            print("【系统广播】🧹 已清空旧经验池，正在等待新的错题反馈...")

        else:
            print(f"【系统广播】❌ 自动演进失败，报错信息:\n{stderr}")

    except Exception as e:
        print(f"【系统广播】❌ 无法启动演进脚本: {e}")
    print("🌟" * 20 + "\n")


@csrf_exempt
@login_required
def submit_feedback(request):

    if request.method == "POST":
        try:
            print("\n" + "📥" * 5 + " 收到演进反馈请求 " + "📥" * 5)
            print(f"原始 POST 数据: {request.POST}")

            record_id = request.POST.get('record_id')
            source_type = request.POST.get('source_type', 'PAD')
            is_correct = request.POST.get('is_correct') == 'true'
            correct_label = request.POST.get('correct_label', '').strip()
            comment = request.POST.get('comment', '')

            if not record_id or record_id in ['undefined', '', 'None']:
                print("❌ 错误：record_id 缺失或无效")
                return JsonResponse({'status': 'error', 'message': 'record_id 缺失'}, status=400)

            try:
                user_info = UserInfo.objects.get(user_id=request.user.id)
            except UserInfo.DoesNotExist:
                print(f"❌ 错误：找不到用户 {request.user.id} 的 UserInfo 记录")
                return JsonResponse({'status': 'error', 'message': '找不到关联用户信息'}, status=400)

            DetectionFeedback.objects.create(
                user=user_info,
                source_type=source_type,
                record_id=int(record_id),
                is_correct=is_correct,
                correct_label=correct_label,
                comment=comment
            )

            if not is_correct and correct_label:
                try:
                    original_record = PestDetectionRecord.objects.get(id=int(record_id))

                    if original_record.result_path:
                        filename = os.path.basename(original_record.result_path)
                        if filename.startswith('detected_'):
                            original_filename = filename.replace('detected_', '', 1)
                        else:
                            original_filename = filename

                        original_image_path = os.path.join(settings.MEDIA_ROOT, original_filename)

                        if os.path.exists(original_image_path):

                            evolve_dataset_dir = os.path.join(settings.MEDIA_ROOT, 'evolve_dataset')
                            images_dir = os.path.join(evolve_dataset_dir, 'images', 'train')
                            labels_dir = os.path.join(evolve_dataset_dir, 'labels', 'train')

                            os.makedirs(images_dir, exist_ok=True)
                            os.makedirs(labels_dir, exist_ok=True)


                            base_filename = f"hard_sample_{record_id}"
                            file_ext = os.path.splitext(original_image_path)[1]

                            new_image_path = os.path.join(images_dir, base_filename + file_ext)
                            shutil.copy2(original_image_path, new_image_path)

                            new_label_path = os.path.join(labels_dir, base_filename + ".txt")
                            class_id = CLASS_MAP.get(correct_label, 0)

                            with open(new_label_path, 'w') as f:

                                f.write(f"{class_id} 0.5000 0.5000 1.0000 1.0000\n")

                            current_samples = len(os.listdir(images_dir))
                            THRESHOLD = 5
                            print(f"✅ 成功归档 ID {record_id}，当前进度: {current_samples}/{THRESHOLD}")

                            if current_samples >= THRESHOLD:
                                print("🔥 进度已满，正在唤醒自动演进大脑...")
                                threading.Thread(target=run_evolution_in_background, daemon=True).start()

                        else:
                            print(f"⚠️ 找不到物理原图: {original_image_path}")

                except PestDetectionRecord.DoesNotExist:
                    print(f"⚠️ 数据库中找不到 ID 为 {record_id} 的原始记录")
                except Exception as inner_e:
                    print(f"⚠️ 数据归档异常: {str(inner_e)}")

            return JsonResponse({'status': 'success'})

        except Exception as e:
            print(f"❌ 严重异常: {str(e)}")
            return JsonResponse({'status': 'error', 'message': str(e)}, status=500)

    return JsonResponse({'status': 'error', 'message': '非法请求'}, status=405)


@login_required
def evolution_feedback_view(request):
    images_dir = os.path.join(settings.MEDIA_ROOT, 'evolve_dataset', 'images', 'train')
    current_samples = len(os.listdir(images_dir)) if os.path.exists(images_dir) else 0
    THRESHOLD = 5
    progress_percent = min(int((current_samples / THRESHOLD) * 100), 100)

    processed_ids = DetectionFeedback.objects.values_list('record_id', flat=True)

    all_raw_records = PestDetectionRecord.objects.exclude(
        id__in=processed_ids
    ).exclude(
        result_path=''
    ).exclude(
        result_path__isnull=True
    ).order_by('-created_at')

    valid_records = []
    for rec in all_raw_records:

        clean_path = rec.result_path.replace('\\', '/').lstrip('/')
        full_path = os.path.join(settings.MEDIA_ROOT, clean_path)

        if os.path.exists(full_path) and "暂无" not in clean_path:
            valid_records.append(rec)

        if len(valid_records) >= 20:
            break

    context = {
        'current_samples': current_samples,
        'threshold': THRESHOLD,
        'progress_percent': progress_percent,
        'records': valid_records,
        'MEDIA_URL': settings.MEDIA_URL,
    }

    return render(request, 'evolution_feedback.html', context)


from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
import json

# 确保导入了这两个模型
from announcement.models import Announcement
from feedback.models import UserFeedback


@csrf_exempt
def api_miniapp_announcements(request):
    """获取最新系统公告"""
    if request.method == "GET":
        try:
            announcements = Announcement.objects.order_by('-created_at')[:5]
            data = []
            for a in announcements:
                data.append({
                    "id": a.id,
                    "title": a.title,
                    "content": a.content,
                    "date": a.created_at.strftime("%Y-%m-%d %H:%M")
                })
            return JsonResponse({"code": 200, "data": data})
        except Exception as e:
            return JsonResponse({"code": 500, "msg": str(e)})


@csrf_exempt
def api_miniapp_submit_feedback(request):
    """提交意见反馈"""
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            user_id = data.get("user_id")
            content = data.get("content")

            if not content:
                return JsonResponse({"code": 400, "msg": "反馈内容不能为空"})

            user = UserInfo.objects.filter(id=user_id).first() if user_id else None

            # 使用我们刚刚在 models.py 里新建的 UserFeedback 类
            UserFeedback.objects.create(
                user=user,
                content=content
            )
            return JsonResponse({"code": 200, "msg": "感谢您的反馈！"})

        except Exception as e:
            return JsonResponse({"code": 500, "msg": f"提交失败: {str(e)}"})

    return JsonResponse({"code": 405, "msg": "仅支持 POST 请求"})