import uuid
import requests
from datetime import datetime
from flask import request
from app.extensions import db
from app.models.tracking import UserSession, ActivityLog


def get_real_ip():
    if request.headers.get("X-Forwarded-For"):
        return request.headers.get("X-Forwarded-For").split(",")[0].strip()
    if request.headers.get("X-Real-IP"):
        return request.headers.get("X-Real-IP")
    return request.remote_addr


def get_location_info(ip_address):
    try:
        response = requests.get(f"http://ip-api.com/json/{ip_address}", timeout=3)
        if response.status_code == 200:
            data = response.json()
            if data.get("status") == "success":
                return {
                    "country": data.get("country"),
                    "city": data.get("city"),
                    "region": data.get("regionName"),
                }
    except Exception:
        return None
    return None


def start_session(user_id):
    session_id = str(uuid.uuid4())
    ip_address = get_real_ip()
    user_agent = request.headers.get("User-Agent")

    UserSession.query.filter_by(user_id=user_id, is_active=True).update({"is_active": False})

    user_session = UserSession(user_id=user_id, session_id=session_id, ip_address=ip_address, user_agent=user_agent)

    location_info = get_location_info(ip_address)
    if location_info:
        user_session.country = location_info.get("country")
        user_session.city = location_info.get("city")

    db.session.add(user_session)
    db.session.commit()

    return user_session


def end_session(session_id):
    user_session = UserSession.query.filter_by(session_id=session_id, is_active=True).first()
    if user_session:
        user_session.end_session()


def log_activity(user_id, session_id, action, endpoint=None, method=None, response_time=None):
    activity_log = ActivityLog(
        user_id=user_id,
        session_id=session_id,
        action=action,
        endpoint=endpoint,
        method=method,
        response_time=response_time,
        timestamp=datetime.utcnow(),
    )
    db.session.add(activity_log)
    db.session.commit()
