from datetime import datetime
from flask import request
from flask_jwt_extended import get_jwt_identity, jwt_required
from app.api import api_bp
from app.models.tracking import UserSession
from app.utils.auth import role_required
from app.utils.response import ok


@api_bp.get("/sessions/my")
@jwt_required()
def my_sessions():
    user_id = get_jwt_identity()
    sessions = UserSession.query.filter_by(user_id=user_id).order_by(UserSession.login_time.desc()).limit(20).all()
    data = [
        {
            "ip_address": session.ip_address,
            "device_type": session.device_type,
            "browser": session.browser,
            "os": session.os,
            "country": session.country,
            "city": session.city,
            "login_time": session.login_time.strftime("%Y-%m-%d %H:%M:%S"),
            "logout_time": session.logout_time.strftime("%Y-%m-%d %H:%M:%S") if session.logout_time else "Active",
            "session_duration": session.session_duration,
            "is_active": session.is_active,
        }
        for session in sessions
    ]
    return ok(data)


@api_bp.get("/admin/sessions")
@role_required("administrator")
def admin_sessions():
    user_id = request.args.get("user_id", type=int)
    query = UserSession.query
    if user_id:
        query = query.filter_by(user_id=user_id)
    sessions = query.order_by(UserSession.login_time.desc()).limit(50).all()
    data = [
        {
            "session_id": session.session_id,
            "user_id": session.user_id,
            "ip_address": session.ip_address,
            "device_type": session.device_type,
            "browser": session.browser,
            "os": session.os,
            "country": session.country,
            "city": session.city,
            "login_time": session.login_time.strftime("%Y-%m-%d %H:%M:%S"),
            "logout_time": session.logout_time.strftime("%Y-%m-%d %H:%M:%S") if session.logout_time else None,
            "last_activity": session.last_activity.strftime("%Y-%m-%d %H:%M:%S"),
            "is_active": session.is_active,
            "session_duration": session.session_duration,
        }
        for session in sessions
    ]
    return ok(data)


@api_bp.get("/admin/activity-stats")
@role_required("administrator")
def activity_stats():
    period = request.args.get("period", "today")
    sessions = UserSession.get_sessions_by_period(period)

    total_sessions = len(sessions)
    unique_users = len(set(s.user_id for s in sessions))
    total_time = sum(s.session_duration for s in sessions if s.session_duration)
    avg_session_time = total_time / total_sessions if total_sessions > 0 else 0

    device_stats = {}
    browser_stats = {}
    os_stats = {}

    for session in sessions:
        device = session.device_type or "unknown"
        device_stats[device] = device_stats.get(device, 0) + 1

        browser = session.browser or "unknown"
        browser_stats[browser] = browser_stats.get(browser, 0) + 1

        os_name = session.os or "unknown"
        os_stats[os_name] = os_stats.get(os_name, 0) + 1

    return ok({
        "period": period,
        "total_sessions": total_sessions,
        "unique_users": unique_users,
        "total_time_minutes": total_time,
        "avg_session_time_minutes": round(avg_session_time, 2),
        "device_stats": device_stats,
        "browser_stats": browser_stats,
        "os_stats": os_stats,
    })
