from flask import Flask
from flask import request
from flask import jsonify

from threading import Thread

from script.report import getReport
from TestEmotionDetector import videoAnalyze

from flask_cors import CORS

import numpy as np
import os
import json
from dotenv import load_dotenv
from utils.auth import validate_api_key

load_dotenv()

port=int(os.getenv("PORT"))


app = Flask(__name__)

CORS(app)


# =====================================
# EMOTION REPORT
# =====================================

@app.route(
    '/api/emotion_analysis_report',
    methods=["POST"]
)
def get_report():
    auth=validate_api_key()
    if auth:
            return auth
    try:

        vids = request.json["vids"]

        reportJsonArr = getReport(
            vids
        )

        return jsonify({

            "success": True,

            "data": reportJsonArr

        })

    except Exception as e:

        return jsonify({

            "success": False,

            "error": str(e)

        })


# =====================================
# START EMOTION ANALYSIS
# =====================================

@app.route(
    '/api/emotion_analysis',
    methods=["POST"]
)
def start_process():
    auth=validate_api_key()
    if auth:
            return auth
    try:

        vid = request.json["vid"]

        vid_url = request.json["vid_url"]

        profile_url = request.json.get(
            "profile_url"
        )

        print()

        print(
            "VIDEO:",
            vid
        )

        print(
            "VIDEO URL:",
            vid_url
        )

        print(
            "PROFILE URL:",
            profile_url
        )

        thread = Thread(

            target=videoAnalyze,

            args=(

                vid,

                vid_url,

                profile_url

            )

        )

        thread.daemon = True

        thread.start()

        return jsonify({

            "started": True,

            "thread_name": str(
                thread.name
            )

        })

    except Exception as e:

        return jsonify({

            "success": False,

            "error": str(e)

        }), 500


# =====================================
# ATTENTION REPORT
# =====================================

@app.route(
    "/api/attention_analysis_report",
    methods=["POST"]
)
def get_attention_report():
    auth=validate_api_key()
    if auth:
            return auth
    try:

        vids = request.json.get(
            "vids",
            []
        )

        results = []

        for vid in vids:

            path = f"reports/{vid}.json"

            if not os.path.exists(
                path
            ):

                results.append({

                    "vid": vid,

                    "status": "not_found"

                })

                continue

            with open(
                path,
                "r"
            ) as f:

                r = json.load(
                    f
                )

            emotions = r.get(
                "emotions",
                {}
            )

            total = sum(
                emotions.values()
            )

            engagement = min(
                100,
                total
            )

            dominant = None

            if emotions:

                dominant = max(

                    emotions,

                    key=emotions.get

                )

            results.append({

                "video": vid,

                "status":

                r.get(
                    "status"
                ),

                "frames":

                r.get(
                    "frames",

                    r.get(
                        "total_frames",
                        0
                    )
                ),

                "matched_frames":

                r.get(
                    "matched_frames",
                    0
                ),

                "engagement_score":

                r.get(
                    "engagement_score",

                    engagement
                ),

                "dominant_emotion":

                r.get(
                    "dominant_emotion",

                    dominant
                ),

                "emotions":

                emotions

            })

        return jsonify({

            "success": True,

            "data": results

        })

    except Exception as e:

        return jsonify({

            "success": False,

            "error": str(e)

        })


# =====================================
# MAIN
# =====================================

@app.route("/api", methods=["GET"])
def welcome():
    return jsonify({
        "message": "Welcome to API"
    })


@app.route("/health")
def health():
    return {
        "status":"ok"
    }



if __name__ == "__main__":

    app.run(

        host='127.0.0.1',

        port=port,

        debug=False,

        use_reloader=False

    )