# Final Code Using API Authentication
import os
from datetime import datetime, timedelta
from typing import Optional
import mysql.connector
from collections import defaultdict
from fastapi import FastAPI, Body, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel, EmailStr, conint
from fastapi.security import APIKeyHeader
from jose import JWTError, jwt
from passlib.context import CryptContext
from core.config import Settings
import google.genai as genai
import json

# FastAPI Application
app = FastAPI()

# API Key Authentication
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)

def get_api_key(api_key_header: str = Depends(api_key_header)):
    if api_key_header == Settings.SECRET_API_KEY:
        return api_key_header
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED, 
        detail="Invalid or missing API Key"
    )

def connect_to_db():
    return mysql.connector.connect(
        host=Settings.DB_HOST,
        user=Settings.DB_USER,
        password=Settings.DB_PASSWORD,
        database=Settings.DB_NAME
    )

def get_user(email: str):
    connection = connect_to_db()
    cursor = connection.cursor(dictionary=True)
    cursor.execute("SELECT * FROM kimai2_users WHERE email = %s", (email,))
    user = cursor.fetchone()
    cursor.close()
    connection.close()
    return user

# Request Model with Validations
class TimeLogRequest(BaseModel):
    Email: EmailStr
    Month: conint(ge=1, le=12)
    Year: conint(ge=2000, le=2100)

def fetch_data(user_email, month, year):
    connection = connect_to_db()
    cursor = connection.cursor()
    query = """SELECT
    t.user AS user,
    t.activity_id AS activity,
    t.project_id AS project,
    t.description AS Description,
    u.username,
    p.name AS project_name,
    a.name AS activity_name
FROM
    kimai2_timesheet t
JOIN
    kimai2_users u ON t.user = u.id
JOIN
    kimai2_projects p ON t.project_id = p.id
JOIN
    kimai2_activities a ON t.activity_id = a.id
WHERE
    t.description IS NOT NULL
    AND p.name NOT IN ('Break')
    AND a.name NOT IN ('NO WORK')
    AND u.email = %s
    AND MONTH(t.start_time) = %s
    AND YEAR(t.start_time) = %s
GROUP BY
    t.user, t.activity_id, t.project_id, t.description, u.username, p.name, a.name
"""
    cursor.execute(query, (user_email, month, year))
    rows = cursor.fetchall()
    cursor.close()
    connection.close()
    return rows

def organize_data(rows):
    project_data = defaultdict(lambda: defaultdict(set))
    for _, activity, project, description, _, project_name, activity_name in rows:
        project_data[project_name][activity_name].add(description)
    
    result = []
    for project_name, activities in project_data.items():
        activity_list = []
        for activity_name, descriptions in activities.items():
            activity_list.append({
                "name": activity_name,
                "descriptions": list(descriptions)
            })
        result.append({
            "project": project_name,
            "activity": activity_list
        })
    return result

def summarize_data(result:str):
    
    key=Settings.GEMINI_API_KEY
    client = genai.Client(api_key=key)
    # Create the prompt string with the dynamic data inserted
    prompt = f"""
    Instruction:  
    Convert the following tasks into professional report sentences using action verbs. Merge similar or duplicate tasks, but keep the original order and headings.
    
    Rules:   
    - Replace only “mam” or “madam” with “Ma'am”; leave all other titles as-is.  
    - Do not change technical terms, syntax, tags, or code.  
    Very Important:
    Preserve all original syntax, formatting, and structural elements used in code, markup, or specialized languages (e.g., HTML, XML, LaTeX, Markdown).
    Do not remove, modify, or restructure any tags, symbols, or domain-specific syntax.
    Return only the cleaned content in the exact structure and format as the input — do not add headings, titles, newlines(\n), summaries, or explanations 
    before or after the output.
    
    Project details:{result}
    """
    # Send prompt to Gemini
    response = client.models.generate_content(model='gemini-1.5-flash-latest', contents=prompt)
    
    return response.text

@app.post("/getTimeLogs")
def getTimeLogs(
    request: TimeLogRequest = Body(...), 
    api_key: str = Depends(get_api_key)
):
    """
    API endpoint to fetch and organize project data for a given user email, month, and year.
    Requires static API Key authentication.
    """
    rows = fetch_data(request.Email, request.Month, request.Year)
    project_data = organize_data(rows)
    return project_data

@app.post("/getSummarizedData")
def getSummarizedData(request: str,
    api_key: str = Depends(get_api_key)):
    """
    Processes and refines raw project task data.
    Improves grammar, eliminates duplicate entries, and structures tasks in a clear, point-wise format.
    Maintains original project and activity titles, and standardizes references to individuals.
    """
    summarized_data = summarize_data(request)
    return {
        "response": {
                "description": summarized_data
            }
    }
