import requests
from datetime import datetime
from models import Employee
from datetime import date
from .desktime import fetch_desktime_productive_hours

DESKTIME_API_KEY = "f9da2cfcf20ff9508002b5a74aa0ff59"
BASE_URL = "https://desktime.com/api/v2/json"

def fetch_desktime_productive_hours(desktime_employee_id, target_date=None):
    """
    Fetch productive hours from Desktime for a given employee and date.
    - desktime_employee_id: the ID mapped to employee in Desktime
    - target_date: 'YYYY-MM-DD' (default: today)
    Returns: float (productive hours) or None on failure
    """
    if not desktime_employee_id:
        return None

    if not target_date:
        target_date = datetime.today().strftime('%Y-%m-%d')

    url = f"{BASE_URL}/employee?apiKey={DESKTIME_API_KEY}&id={desktime_employee_id}&date={target_date}"

    try:
        response = requests.get(url)
        data = response.json()
        if 'data' in data and 'summary' in data['data']:
            seconds = data['data']['summary'].get('productive_time', 0)
            return round(seconds / 3600, 2)  # Convert to hours
    except Exception as e:
        print(f"Desktime API Error: {e}")
    return None

def sync_all_desktime_data():
    today = date.today()
    employees = Employee.query.filter(Employee.desktime_id.isnot(None)).all()
    result = {"synced": 0, "errors": 0}

    for emp in employees:
        try:
            fetch_desktime_productive_hours(emp, today)
            result["synced"] += 1
        except Exception as e:
            print(f"Error syncing {emp.full_name}: {e}")
            result["errors"] += 1

    return result