import cv2
import os
from django.http import StreamingHttpResponse, JsonResponse
from django.shortcuts import render
from ultralytics import YOLO

os.environ['ULTRALYTICS_OFFLINE'] = 'True'

os.environ['no_proxy'] = '*'

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
MODEL_PATH = os.path.join(CURRENT_DIR, "best.pt")

if not os.path.exists(MODEL_PATH):
    raise FileNotFoundError(f"❌ 关键错误：在 {MODEL_PATH} 未找到模型文件！")

yolo_model = YOLO(MODEL_PATH)

from .engine import InferenceGate
from .tracker import PowerAuditor

gate = InferenceGate(sensitivity=0.015)
auditor = PowerAuditor(yolo_flops=8.5)
camera = cv2.VideoCapture(0)

def edge_dashboard(request):

    return render(request, 'edge_core/dashboard.html', {'active_page': 'edge'})

def gen_frames():

    while True:
        success, frame = camera.read()
        if not success:
            break

        active, _ = gate.is_active(frame)
        auditor.record(active)

        if active:

            results = yolo_model(frame, verbose=False)
            frame = results[0].plot()
            status_text = "MODE: PRECISION (YOLO ACTIVE)"
            color = (0, 0, 255)
        else:
            frame = cv2.addWeighted(frame, 0.4, frame, 0, 0)
            status_text = "MODE: ECO-SAVING (IDLE)"
            color = (0, 255, 0)

        cv2.putText(frame, status_text, (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)

        ret, buffer = cv2.imencode('.jpg', frame)
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')

def video_feed(request):
    """视频流接口"""
    return StreamingHttpResponse(gen_frames(), content_type='multipart/x-mixed-replace; boundary=frame')

def get_metrics(request):
    """实时数据接口"""
    return JsonResponse(auditor.get_metrics())