from fastapi import APIRouter, HTTPException, Body
from database import get_connection
from crm_notifications import create_crm_notification
from schemas import TaskCreate
from pydantic import BaseModel, Field, ConfigDict
from google import genai
from dotenv import load_dotenv
from pathlib import Path
from email_service import send_email
from typing import Optional, List
import os
import json



# =========================================================
# LOAD BACKEND .ENV
# =========================================================

BASE_DIR = Path(__file__).resolve().parent.parent

load_dotenv(BASE_DIR / ".env")

print("ENV FILE:", BASE_DIR / ".env")
print("GEMINI KEY FOUND:", bool(os.getenv("GEMINI_API_KEY")))


# =========================================================
# ROUTER
# =========================================================

router = APIRouter(
    prefix="/tasks",
    tags=["Tasks"]
)


# =========================================================
# GEMINI CLIENT
# =========================================================

gemini_client = genai.Client(
    api_key=os.getenv("GEMINI_API_KEY")
)


# =========================================================
# PYDANTIC MODELS
# =========================================================


class TaskImproveRequest(BaseModel):
    title: str = ""
    description: str = ""


class TaskProgressUpdate(BaseModel):
    progress: int = Field(ge=0, le=100)


class TaskStatusUpdate(BaseModel):
    status: str


class TaskSubmissionCreate(BaseModel):
    model_config = ConfigDict(populate_by_name=True)

    employee_id: str = Field(
        ...,
        alias="employeeId"
    )

    note: str = Field(
        ...,
        min_length=1
    )

    progress: int = Field(
        ...,
        ge=0,
        le=100
    )

# =========================================================
# AI IMPROVE TASK
# =========================================================

@router.post("/improve")
def improve_task(data: TaskImproveRequest):

    if (
        not data.title.strip()
        and not data.description.strip()
    ):
        raise HTTPException(
            status_code=400,
            detail="Task title or description is required."
        )

    try:

        prompt = f"""
You are a professional project/task management assistant.

Improve the following task so that it is:

- professional
- clear
- actionable
- concise
- suitable for assigning to an employee

Current Task Title:
{data.title}

Current Task Description:
{data.description}

Return ONLY valid JSON in exactly this format:

{{
    "title": "Improved task title",
    "description": "Improved task description"
}}
"""

        response = gemini_client.models.generate_content(
            model="gemini-3.6-flash",
            contents=prompt,
            config={
                "temperature": 0.4,
                "response_mime_type": "application/json"
            }
        )

        result = json.loads(response.text)

        return {
            "status": "success",
            "title": result.get(
                "title",
                data.title
            ),
            "description": result.get(
                "description",
                data.description
            )
        }

    except Exception as e:

        print(
            "GEMINI IMPROVE ERROR:",
            str(e)
        )

        raise HTTPException(
            status_code=500,
            detail=f"AI improvement failed: {str(e)}"
        )


# =========================================================
# SEND TASK ASSIGNMENT EMAIL
# =========================================================

def send_task_assignment_email(
    employee_name,
    employee_email,
    task
):

    subject = f"New Task Assigned: {task.title}"

    html_content = f"""
    <!DOCTYPE html>

    <html>

    <head>

        <meta charset="UTF-8">

        <title>New Task Assigned</title>

    </head>

    <body
        style="
            margin:0;
            padding:0;
            background:#f5f7fb;
            font-family:Arial,Helvetica,sans-serif;
        "
    >

        <div
            style="
                max-width:650px;
                margin:30px auto;
                background:#ffffff;
                border-radius:12px;
                overflow:hidden;
                box-shadow:0 4px 15px rgba(0,0,0,0.08);
            "
        >

            <div
                style="
                    background:#4f46e5;
                    padding:25px;
                    color:white;
                "
            >

                <h2
                    style="
                        margin:0;
                        font-size:24px;
                    "
                >
                    📋 New Task Assigned
                </h2>

                <p
                    style="
                        margin:8px 0 0;
                        opacity:0.9;
                    "
                >
                    Kinetic CRM
                </p>

            </div>

            <div
                style="
                    padding:30px;
                    color:#333333;
                "
            >

                <p>
                    Hello
                    <strong>{employee_name}</strong>,
                </p>

                <p>
                    A new task has been assigned to you.
                    Please review the task details below.
                </p>

                <div
                    style="
                        margin-top:25px;
                        padding:18px;
                        background:#f8f9ff;
                        border-left:4px solid #4f46e5;
                        border-radius:6px;
                    "
                >

                    <div
                        style="
                            font-size:13px;
                            color:#666;
                            margin-bottom:5px;
                        "
                    >
                        TASK
                    </div>

                    <div
                        style="
                            font-size:20px;
                            font-weight:bold;
                            color:#222;
                        "
                    >
                        {task.title}
                    </div>

                </div>

                <div
                    style="
                        margin-top:20px;
                    "
                >

                    <strong>
                        Description
                    </strong>

                    <p
                        style="
                            line-height:1.6;
                            color:#555;
                        "
                    >
                        {task.description or "No description provided."}
                    </p>

                </div>

                <table
                    style="
                        width:100%;
                        margin-top:20px;
                        border-collapse:collapse;
                    "
                >

                    <tr>

                        <td
                            style="
                                padding:10px;
                                border-bottom:1px solid #eee;
                                font-weight:bold;
                            "
                        >
                            Department
                        </td>

                        <td
                            style="
                                padding:10px;
                                border-bottom:1px solid #eee;
                            "
                        >
                            {task.department or "N/A"}
                        </td>

                    </tr>

                    <tr>

                        <td
                            style="
                                padding:10px;
                                border-bottom:1px solid #eee;
                                font-weight:bold;
                            "
                        >
                            Designation
                        </td>

                        <td
                            style="
                                padding:10px;
                                border-bottom:1px solid #eee;
                            "
                        >
                            {task.designation or "N/A"}
                        </td>

                    </tr>

                    <tr>

                        <td
                            style="
                                padding:10px;
                                border-bottom:1px solid #eee;
                                font-weight:bold;
                            "
                        >
                            Priority
                        </td>

                        <td
                            style="
                                padding:10px;
                                border-bottom:1px solid #eee;
                            "
                        >
                            {task.priority}
                        </td>

                    </tr>

                    <tr>

                        <td
                            style="
                                padding:10px;
                                border-bottom:1px solid #eee;
                                font-weight:bold;
                            "
                        >
                            Due Date
                        </td>

                        <td
                            style="
                                padding:10px;
                                border-bottom:1px solid #eee;
                            "
                        >
                            {task.endDate}
                        </td>

                    </tr>

                    <tr>

                        <td
                            style="
                                padding:10px;
                                font-weight:bold;
                            "
                        >
                            Due Time
                        </td>

                        <td
                            style="
                                padding:10px;
                            "
                        >
                            {task.endTime or "N/A"}
                        </td>

                    </tr>

                </table>

                <p
                    style="
                        margin-top:30px;
                        color:#555;
                    "
                >
                    Please complete the task before the
                    specified deadline.
                </p>

                <p
                    style="
                        margin-top:25px;
                    "
                >
                    Regards,<br>
                    <strong>Kinetic CRM</strong>
                </p>

            </div>

            <div
                style="
                    padding:15px 30px;
                    background:#f8f9fa;
                    color:#888;
                    font-size:12px;
                    text-align:center;
                "
            >
                This is an automated task notification.
                Please do not reply to this email.
            </div>

        </div>

    </body>

    </html>
    """

    send_email(
        to_email=employee_email,
        subject=subject,
        html_content=html_content
    )


# =========================================================
# CREATE TASK
# =========================================================

@router.post("/")
def create_task(task: TaskCreate):

    connection = get_connection()
    cursor = connection.cursor()

    try:

        # -------------------------------------------------
        # CREATE TASK
        # -------------------------------------------------

        sql = """
        INSERT INTO tasks
        (
            created_by,
            title,
            description,
            department,
            designation,
            end_date,
            end_time,
            priority,
            status
        )
        VALUES
        (
            %s,
            %s,
            %s,
            %s,
            %s,
            %s,
            %s,
            %s,
            %s
        )
        """

        cursor.execute(
            sql,
            (
                task.created_by,
                task.title,
                task.description,
                task.department,
                task.designation,
                task.endDate,
                task.endTime,
                task.priority,
                task.status
            )
        )

        task_id = cursor.lastrowid

        # -------------------------------------------------
        # ASSIGNEES
        # -------------------------------------------------

        for employee_id in task.assignees:

            cursor.execute(
                """
                INSERT INTO task_assignees
                (
                    task_id,
                    employee_id
                )
                VALUES
                (
                    %s,
                    %s
                )
                """,
                (
                    task_id,
                    employee_id
                )
            )

        # -------------------------------------------------
        # REMINDERS
        # -------------------------------------------------

        if (
            task.reminder
            and task.reminder.get("enabled")
        ):

            reminders = task.reminder.get(
                "reminders",
                []
            )

            for reminder in reminders:

                cursor.execute(
                    """
                    INSERT INTO task_reminders
                    (
                        task_id,
                        amount,
                        unit,
                        channels
                    )
                    VALUES
                    (
                        %s,
                        %s,
                        %s,
                        %s
                    )
                    """,
                    (
                        task_id,
                        reminder["amount"],
                        reminder["unit"],
                        json.dumps(
                            reminder["channels"]
                        )
                    )
                )

        # -------------------------------------------------
        # RECURRING TASK
        # -------------------------------------------------

        if (
            task.recurring
            and task.recurring.get("enabled")
        ):

            recurring = task.recurring

            cursor.execute(
                """
                INSERT INTO task_recurrence
                (
                    task_id,
                    enabled,
                    type,
                    repeat_interval,
                    days,
                    repeat_time,
                    times,
                    end_date
                )
                VALUES
                (
                    %s,
                    %s,
                    %s,
                    %s,
                    %s,
                    %s,
                    %s,
                    %s
                )
                """,
                (
                    task_id,
                    recurring.get("enabled"),
                    recurring.get("type"),
                    recurring.get("interval"),
                    json.dumps(
                        recurring.get(
                            "days",
                            []
                        )
                    ),
                    recurring.get("time"),
                    json.dumps(
                        recurring.get(
                            "times",
                            []
                        )
                    ),
                    recurring.get("endDate")
                )
            )

        # -------------------------------------------------
        # COMMIT
        # -------------------------------------------------

        connection.commit()
        for employee_id in task.assignees:

          try:

           create_crm_notification(
            employee_id=employee_id,
            title="New Task Assigned",
            message=f"You have been assigned a new task: {task.title}",
            notification_type="task"
           )

          except Exception as notification_error:

           print(
             "TASK CRM NOTIFICATION ERROR:",
             str(notification_error)
            )

        # -------------------------------------------------
        # SEND EMAIL
        # -------------------------------------------------

        email_results = []

        for employee_id in task.assignees:

            try:

                cursor.execute(
                    """
                    SELECT
                        fullName,
                        email
                    FROM employees
                    WHERE employeeId = %s
                    """,
                    (employee_id,)
                )

                employee = cursor.fetchone()

                if not employee:

                    email_results.append({
                        "employee_id": employee_id,
                        "status": "employee_not_found"
                    })

                    continue

                employee_name = employee[0]
                employee_email = employee[1]

                if not employee_email:

                    email_results.append({
                        "employee_id": employee_id,
                        "status": "email_not_found"
                    })

                    continue

                send_task_assignment_email(
                    employee_name=employee_name,
                    employee_email=employee_email,
                    task=task
                )

                email_results.append({
                    "employee_id": employee_id,
                    "email": employee_email,
                    "status": "sent"
                })

            except Exception as email_error:

                print(
                    "TASK EMAIL ERROR:",
                    str(email_error)
                )

                email_results.append({
                    "employee_id": employee_id,
                    "status": "failed",
                    "error": str(email_error)
                })

        return {
            "status": "success",
            "message": "Task created successfully",
            "task_id": task_id,
            "created_by": task.created_by,
            "emails": email_results
        }

    except Exception as e:

        connection.rollback()

        print(
            "CREATE TASK ERROR:",
            str(e)
        )

        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

    finally:

        cursor.close()
        connection.close()


# =========================================================
# GET ALL TASKS
# =========================================================
# =========================================================
# GET ALL TASKS
# =========================================================

@router.get("/")
def get_tasks():

    connection = get_connection()
    cursor = connection.cursor(dictionary=True)

    try:

        # =================================================
        # GET ALL TASKS
        # =================================================

        cursor.execute(
            """
            SELECT
                t.id,
                t.created_by,

                e.fullName AS created_by_name,
                e.email AS created_by_email,

                t.title,
                t.description,
                t.department,
                t.designation,
                t.end_date,
                t.end_time,
                t.priority,
                t.status,
                t.progress,
                t.created_at,
                t.updated_at,

                (
                    SELECT COUNT(*)
                    FROM task_submissions ts
                    WHERE ts.task_id = t.id
                ) AS submission_count

            FROM tasks t

            LEFT JOIN employees e
                ON e.employeeId = t.created_by

            ORDER BY t.id DESC
            """
        )

        tasks = cursor.fetchall()

        # =================================================
        # PROCESS EACH TASK
        # =================================================

        for task in tasks:

            # -------------------------------------------------
            # DATE / TIME
            # -------------------------------------------------

            task["endDate"] = (
                task["end_date"].isoformat()
                if task["end_date"]
                else None
            )

            task["endTime"] = (
                str(task["end_time"])
                if task["end_time"]
                else None
            )

            # -------------------------------------------------
            # BASIC VALUES
            # -------------------------------------------------

            task["progress"] = int(
                task.get("progress") or 0
            )

            task["submission_count"] = int(
                task.get("submission_count") or 0
            )

            # -------------------------------------------------
            # CREATED / UPDATED DATE
            # -------------------------------------------------

            if task.get("created_at"):
                task["created_at"] = (
                    task["created_at"].isoformat()
                )

            if task.get("updated_at"):
                task["updated_at"] = (
                    task["updated_at"].isoformat()
                )

            # -------------------------------------------------
            # REMOVE ORIGINAL DATE COLUMNS
            # -------------------------------------------------

            task.pop("end_date", None)
            task.pop("end_time", None)

            # =================================================
            # GET ASSIGNEES
            # =================================================

            cursor.execute(
                """
                SELECT employee_id
                FROM task_assignees
                WHERE task_id = %s
                """,
                (task["id"],)
            )

            rows = cursor.fetchall()

            task["assignees"] = [
                str(row["employee_id"])
                for row in rows
            ]

            # =================================================
            # GET ALL SUBMISSIONS
            # =================================================

            cursor.execute(
                """
                SELECT
                    ts.id,
                    ts.task_id,
                    ts.employee_id,

                    e.fullName AS employee_name,

                    ts.note,
                    ts.progress,
                    ts.status,
                    ts.manager_feedback,
                    ts.task_rating,
                    ts.submitted_at

                FROM task_submissions ts

                LEFT JOIN employees e
                    ON e.employeeId = ts.employee_id

                WHERE ts.task_id = %s

                ORDER BY
                    ts.submitted_at DESC,
                    ts.id DESC
                """,
                (task["id"],)
            )

            submissions = cursor.fetchall()

            # =================================================
            # NORMALIZE SUBMISSIONS
            # =================================================

            for submission in submissions:

                submission["progressAtSubmission"] = (
                    int(submission.get("progress") or 0)
                )

                submission["submittedAt"] = (
                    submission["submitted_at"].isoformat()
                    if submission.get("submitted_at")
                    else None
                )

                submission["submittedBy"] = (
                    submission.get("employee_name")
                    or submission.get("employee_id")
                    or "Employee"
                )

                submission["managerFeedback"] = (
                    submission.get("manager_feedback")
                    or ""
                )
                submission["taskRating"] = (
                    submission.get("task_rating")
                    or 0
                )
 
                # Remove DB-only fields
                submission.pop("employee_name", None)
                submission.pop("progress", None)
                submission.pop("submitted_at", None)
                submission.pop("manager_feedback", None)

            # =================================================
            # ATTACH SUBMISSIONS TO TASK
            # =================================================

            task["submissions"] = submissions

            # Keep count synced with actual submissions
            task["submission_count"] = len(submissions)

        # =================================================
        # RETURN TASKS
        # =================================================

        print(
            "GET TASKS:",
            len(tasks),
            "tasks loaded"
        )

        for task in tasks:
            print(
                "TASK",
                task["id"],
                "SUBMISSIONS:",
                len(task.get("submissions", []))
            )

        return tasks

    except Exception as e:

        print(
            "GET TASKS ERROR:",
            str(e)
        )

        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

    finally:

        cursor.close()
        connection.close()
#==============================================
# GET SINGLE TASK
# =========================================================

@router.get("/{task_id}")
def get_task(task_id: int):

    connection = get_connection()
    cursor = connection.cursor(dictionary=True)

    try:

        cursor.execute(
            """
            SELECT
                t.id,
                t.created_by,

                e.fullName AS created_by_name,
                e.email AS created_by_email,

                t.title,
                t.description,
                t.department,
                t.designation,
                t.end_date,
                t.end_time,
                t.priority,
                t.status,
                t.progress,
                t.created_at,
                t.updated_at

            FROM tasks t

            LEFT JOIN employees e
                ON e.employeeId = t.created_by

            WHERE t.id = %s
            """,
            (task_id,)
        )

        task = cursor.fetchone()

        if not task:

            raise HTTPException(
                status_code=404,
                detail="Task not found"
            )

        task["endDate"] = (
            task["end_date"].isoformat()
            if task["end_date"]
            else None
        )
        

        task["endTime"] = (
            str(task["end_time"])
            if task["end_time"]
            else None
        )

        if task.get("created_at"):
            task["created_at"] = task["created_at"].isoformat()

        if task.get("updated_at"):
            task["updated_at"] = task["updated_at"].isoformat()

        task.pop("end_date", None)
        task.pop("end_time", None)

        # -------------------------------------------------
        # ASSIGNEES
        # -------------------------------------------------

        cursor.execute(
            """
            SELECT
                employee_id
            FROM task_assignees
            WHERE task_id = %s
            """,
            (task_id,)
        )

        rows = cursor.fetchall()

        task["assignees"] = [
            row["employee_id"]
            for row in rows
        ]

        # -------------------------------------------------
        # SUBMISSIONS
        # -------------------------------------------------

        cursor.execute(
            """
            SELECT
                ts.id,
                ts.task_id,
                ts.employee_id,
                e.fullName AS employee_name,
                ts.note,
                ts.progress,
                ts.status,
                ts.manager_feedback,
                ts.task_rating,
                ts.submitted_at

            FROM task_submissions ts

            LEFT JOIN employees e
                ON e.employeeId = ts.employee_id

            WHERE ts.task_id = %s

            ORDER BY ts.submitted_at DESC
            """,
            (task_id,)
        )

        submissions = cursor.fetchall()

        for submission in submissions:

            submission["progressAtSubmission"] = (
                submission["progress"]
            )

            submission["submittedAt"] = (
                submission["submitted_at"].isoformat()
                if submission["submitted_at"]
                else None
            )

            submission["submittedBy"] = (
                submission["employee_name"]
                or submission["employee_id"]
            )
            submission["taskRating"] = (
              submission.get("task_rating")
               or 0
            )

            submission.pop("submitted_at", None)
            submission.pop("employee_name", None)
            submission.pop("progress", None)

        task["submissions"] = submissions

        return task

    except HTTPException:
        raise

    except Exception as e:

        print(
            "GET SINGLE TASK ERROR:",
            str(e)
        )

        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

    finally:

        cursor.close()
        connection.close()


# =========================================================
# GET TASK SUBMISSIONS
# =========================================================

@router.get("/{task_id}/submissions")
def get_task_submissions(task_id: int):

    connection = get_connection()
    cursor = connection.cursor(dictionary=True)

    try:

        # Check task first

        cursor.execute(
            """
            SELECT id
            FROM tasks
            WHERE id = %s
            """,
            (task_id,)
        )

        task = cursor.fetchone()

        if not task:

            raise HTTPException(
                status_code=404,
                detail="Task not found"
            )

        cursor.execute(
            """
            SELECT
                ts.id,
                ts.task_id,
                ts.employee_id,
                e.fullName AS employee_name,
                ts.note,
                ts.progress,
                ts.status,
                ts.manager_feedback,
                ts.task_rating,
                ts.submitted_at

            FROM task_submissions ts

            LEFT JOIN employees e
                ON e.employeeId = ts.employee_id

            WHERE ts.task_id = %s

            ORDER BY ts.submitted_at DESC
            """,
            (task_id,)
        )

        submissions = cursor.fetchall()

        for submission in submissions:

            submission["progressAtSubmission"] = (
                submission["progress"]
            )

            submission["submittedAt"] = (
                submission["submitted_at"].isoformat()
                if submission["submitted_at"]
                else None
            )

            submission["submittedBy"] = (
                submission["employee_name"]
                or submission["employee_id"]
            )
            submission["taskRating"] = (
                submission.get("task_rating")
                or 0
            )
            submission.pop("submitted_at", None)
            submission.pop("employee_name", None)
            submission.pop("progress", None)

        return {
            "status": "success",
            "task_id": task_id,
            "submissions": submissions
        }

    except HTTPException:
        raise

    except Exception as e:

        print(
            "GET SUBMISSIONS ERROR:",
            str(e)
        )

        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

    finally:

        cursor.close()
        connection.close()


# =========================================================
# SAVE PROGRESS
# =========================================================
@router.put("/{task_id}/progress")
def update_task_progress(
    task_id: int,
    data: TaskProgressUpdate = Body(...)
):

    connection = get_connection()
    cursor = connection.cursor()

    try:

        cursor.execute(
            """
            SELECT
                id
            FROM tasks
            WHERE id = %s
            """,
            (task_id,)
        )

        task = cursor.fetchone()

        if not task:

            raise HTTPException(
                status_code=404,
                detail="Task not found"
            )

        progress = int(
            data.progress
        )

        if progress >= 100:

            status = "Completed"

        elif progress > 0:

            status = "In Progress"

        else:

            status = "Pending"

        cursor.execute(
            """
            UPDATE tasks
            SET
                progress = %s,
                status = %s,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = %s
            """,
            (
                progress,
                status,
                task_id
            )
        )

        connection.commit()

        return {
            "status": "success",
            "message": "Progress updated successfully",
            "task_id": task_id,
            "progress": progress,
            "task_status": status
        }

    except HTTPException:

        connection.rollback()
        raise

    except Exception as e:

        connection.rollback()

        print(
            "UPDATE PROGRESS ERROR:",
            str(e)
        )

        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

    finally:

        cursor.close()
        connection.close()
#=========================================================
# SUBMIT TASK FOR REVIEW
# =========================================================

# =========================================================
# SUBMIT TASK FOR REVIEW
# =========================================================

@router.post("/{task_id}/submit")
def submit_task_for_review(
    task_id: int,
    data: TaskSubmissionCreate = Body(...)
):

    employee_id = data.employee_id.strip()
    note = data.note.strip()

    if not employee_id:
        raise HTTPException(
            status_code=400,
            detail="Employee ID is required."
        )

    if not note:
        raise HTTPException(
            status_code=400,
            detail="Work note is required."
        )

    connection = get_connection()
    cursor = connection.cursor(dictionary=True)

    try:

        # =================================================
        # GET TASK + MANAGER
        # =================================================

        cursor.execute(
            """
            SELECT
                t.id,
                t.title,
                t.status,
                t.created_by,
                manager.fullName AS manager_name,
                manager.email AS manager_email

            FROM tasks t

            LEFT JOIN employees manager
                ON manager.employeeId = t.created_by

            WHERE t.id = %s
            """,
            (task_id,)
        )

        task = cursor.fetchone()

        if not task:

            raise HTTPException(
                status_code=404,
                detail="Task not found"
            )

        # =================================================
        # GET EMPLOYEE
        # =================================================

        cursor.execute(
            """
            SELECT
                employeeId,
                fullName,
                email
            FROM employees
            WHERE employeeId = %s
            """,
            (employee_id,)
        )

        employee = cursor.fetchone()

        if not employee:

            raise HTTPException(
                status_code=404,
                detail="Employee not found."
            )

        # =================================================
        # CHECK TASK ASSIGNMENT
        # =================================================

        cursor.execute(
            """
            SELECT
                task_id,
                employee_id
            FROM task_assignees

            WHERE task_id = %s
            AND employee_id = %s
            """,
            (
                task_id,
                employee_id
            )
        )

        assignment = cursor.fetchone()

        if not assignment:

            raise HTTPException(
                status_code=403,
                detail="This task is not assigned to this employee."
            )

        # =================================================
        # INSERT SUBMISSION
        # =================================================

        cursor.execute(
            """
            INSERT INTO task_submissions
            (
                task_id,
                employee_id,
                note,
                progress,
                status
            )

            VALUES
            (
                %s,
                %s,
                %s,
                %s,
                %s
            )
            """,
            (
                task_id,
                employee_id,
                note,
                data.progress,
                "In Review"
            )
        )

        submission_id = cursor.lastrowid

        # =================================================
        # UPDATE TASK
        # =================================================

        cursor.execute(
            """
            UPDATE tasks

            SET
                progress = %s,
                status = %s,
                updated_at = CURRENT_TIMESTAMP

            WHERE id = %s
            """,
            (
                data.progress,
                "In Review",
                task_id
            )
        )

        connection.commit()
        # =================================================
# CRM NOTIFICATION TO MANAGER
# =================================================

        try:

           create_crm_notification(
             employee_id=task["created_by"],
             title="Task Submitted for Review",
             message=(
               f"{employee['fullName']} has submitted "
               f"the task '{task['title']}' for your review."
             ),
             notification_type="task_submission"
            )

        except Exception as notification_error:

           print(
             "TASK SUBMISSION CRM NOTIFICATION ERROR:",
             str(notification_error)
            )

        # =================================================
        # SEND EMAIL TO MANAGER
        # =================================================

        manager_email_status = "not_sent"

        if task.get("manager_email"):

            try:

                manager_subject = (
                    f"Task Submitted for Review: {task['title']}"
                )

                manager_html = f"""
                <!DOCTYPE html>

                <html>

                <body
                    style="
                        margin:0;
                        padding:0;
                        background:#f5f7fb;
                        font-family:Arial,Helvetica,sans-serif;
                    "
                >

                    <div
                        style="
                            max-width:650px;
                            margin:30px auto;
                            background:#ffffff;
                            border-radius:12px;
                            overflow:hidden;
                            box-shadow:0 4px 15px rgba(0,0,0,0.08);
                        "
                    >

                        <div
                            style="
                                background:#4f46e5;
                                padding:25px;
                                color:white;
                            "
                        >

                            <h2 style="margin:0;">
                                📋 Task Submitted for Review
                            </h2>

                            <p style="margin:8px 0 0;">
                                Kinetic CRM
                            </p>

                        </div>

                        <div
                            style="
                                padding:30px;
                                color:#333;
                            "
                        >

                            <p>
                                Hello
                                <strong>
                                    {task.get("manager_name") or "Manager"}
                                </strong>,
                            </p>

                            <p>
                                An employee has submitted a task
                                for your review.
                            </p>

                            <div
                                style="
                                    margin-top:20px;
                                    padding:18px;
                                    background:#f8f9ff;
                                    border-left:4px solid #4f46e5;
                                    border-radius:6px;
                                "
                            >

                                <strong>Task</strong>

                                <div
                                    style="
                                        font-size:20px;
                                        font-weight:bold;
                                        margin-top:6px;
                                    "
                                >
                                    {task["title"]}
                                </div>

                            </div>

                            <table
                                style="
                                    width:100%;
                                    margin-top:20px;
                                    border-collapse:collapse;
                                "
                            >

                                <tr>

                                    <td
                                        style="
                                            padding:10px;
                                            border-bottom:1px solid #eee;
                                            font-weight:bold;
                                        "
                                    >
                                        Submitted By
                                    </td>

                                    <td
                                        style="
                                            padding:10px;
                                            border-bottom:1px solid #eee;
                                        "
                                    >
                                        {employee["fullName"]}
                                    </td>

                                </tr>

                                <tr>

                                    <td
                                        style="
                                            padding:10px;
                                            border-bottom:1px solid #eee;
                                            font-weight:bold;
                                        "
                                    >
                                        Progress
                                    </td>

                                    <td
                                        style="
                                            padding:10px;
                                            border-bottom:1px solid #eee;
                                        "
                                    >
                                        {data.progress}%
                                    </td>

                                </tr>

                                <tr>

                                    <td
                                        style="
                                            padding:10px;
                                            font-weight:bold;
                                        "
                                    >
                                        Status
                                    </td>

                                    <td
                                        style="
                                            padding:10px;
                                        "
                                    >
                                        In Review
                                    </td>

                                </tr>

                            </table>

                            <div
                                style="
                                    margin-top:25px;
                                    padding:15px;
                                    background:#f8f9fa;
                                    border-radius:6px;
                                "
                            >

                                <strong>Employee Note</strong>

                                <p
                                    style="
                                        line-height:1.6;
                                        color:#555;
                                    "
                                >
                                    {note}
                                </p>

                            </div>

                            <p style="margin-top:30px;">
                                Please review the submission
                                and update the task status accordingly.
                            </p>

                            <p style="margin-top:25px;">
                                Regards,<br>
                                <strong>Kinetic CRM</strong>
                            </p>

                        </div>

                        <div
                            style="
                                padding:15px 30px;
                                background:#f8f9fa;
                                color:#888;
                                font-size:12px;
                                text-align:center;
                            "
                        >
                            This is an automated notification.
                        </div>

                    </div>

                </body>

                </html>
                """

                send_email(
                    to_email=task["manager_email"],
                    subject=manager_subject,
                    html_content=manager_html
                )

                manager_email_status = "sent"

            except Exception as email_error:

                print(
                    "MANAGER SUBMISSION EMAIL ERROR:",
                    str(email_error)
                )

                manager_email_status = "failed"

        else:

            print(
                "MANAGER EMAIL NOT FOUND FOR TASK:",
                task_id
            )

        # =================================================
        # RESPONSE
        # =================================================

        return {

            "status": "success",

            "message": (
                "Task submitted for review successfully. "
                "Manager has been notified."
            ),

            "task_id": task_id,

            "submission_id": submission_id,

            "employee_id": employee_id,

            "employee_name": employee["fullName"],

            "manager_id": task["created_by"],

            "manager_name": task.get("manager_name"),

            "manager_email": task.get("manager_email"),

            "manager_email_status": manager_email_status,

            "note": note,

            "progress": data.progress,

            "task_status": "In Review"
        }

    except HTTPException:

        connection.rollback()
        raise

    except Exception as e:

        connection.rollback()

        print(
            "SUBMIT TASK ERROR:",
            str(e)
        )

        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

    finally:

        cursor.close()
        connection.close()
class ManagerReviewUpdate(BaseModel):
    status: str
    manager_feedback: str = ""
    task_rating: Optional[int] = None

# =========================================================
# MANAGER REVIEW TASK
# =========================================================
# =========================================================
# MANAGER REVIEW TASK
# =========================================================

@router.put("/{task_id}/review")
def manager_review_task(
    task_id: int,
    data: ManagerReviewUpdate = Body(...)
):

    allowed_statuses = [
        "In Review",
        "Completed",
        "Rework"
    ]

    # -----------------------------------------------------
    # VALIDATE STATUS
    # -----------------------------------------------------

    if data.status not in allowed_statuses:
        raise HTTPException(
            status_code=400,
            detail=(
                "Invalid review status. "
                "Allowed: In Review, Completed, Rework"
            )
        )

    # -----------------------------------------------------
    # VALIDATE RATING
    # -----------------------------------------------------

    if data.task_rating is not None:

        if data.task_rating < 1 or data.task_rating > 5:
            raise HTTPException(
                status_code=400,
                detail="Task rating must be between 1 and 5."
            )

        # Rating sirf Completed task ke liye allowed hai
        if data.status != "Completed":
            raise HTTPException(
                status_code=400,
                detail="Rating can only be saved when task is Completed."
            )

    connection = get_connection()
    cursor = connection.cursor(dictionary=True)

    try:

        # =================================================
        # CHECK TASK
        # =================================================

        cursor.execute(
            """
            SELECT
                id,
                title,
                status,
                progress
            FROM tasks
            WHERE id = %s
            """,
            (task_id,)
        )

        task = cursor.fetchone()

        if not task:

            raise HTTPException(
                status_code=404,
                detail="Task not found"
            )

        # =================================================
        # GET LATEST SUBMISSION
        # =================================================

        cursor.execute(
            """
            SELECT
                id,
                employee_id,
                progress,
                note,
                status,
                manager_feedback,
                task_rating
            FROM task_submissions
            WHERE task_id = %s
            ORDER BY submitted_at DESC, id DESC
            LIMIT 1
            """,
            (task_id,)
        )

        submission = cursor.fetchone()

        if not submission:

            raise HTTPException(
                status_code=400,
                detail="No employee submission found for this task."
            )

        # =================================================
        # UPDATE SUBMISSION
        # =================================================
        #
        # IMPORTANT:
        # COALESCE ka use isliye kiya hai taaki
        # Save Feedback / Rework ke time existing rating
        # accidentally NULL na ho.
        #
        # Agar task_rating diya gaya hai -> new rating save hogi
        # Agar task_rating None hai -> old rating same rahegi
        # =================================================

        cursor.execute(
            """
            UPDATE task_submissions
            SET
                manager_feedback = %s,
                status = %s,
                task_rating = COALESCE(%s, task_rating)
            WHERE id = %s
            """,
            (
                data.manager_feedback.strip(),
                data.status,
                data.task_rating,
                submission["id"]
            )
        )

        # =================================================
        # TASK STATUS / PROGRESS
        # =================================================

        if data.status == "Completed":

            task_progress = 100

        elif data.status == "Rework":

            task_progress = int(
                submission["progress"] or 0
            )

        else:

            task_progress = int(
                submission["progress"] or 0
            )

        # =================================================
        # UPDATE MAIN TASK
        # =================================================

        cursor.execute(
            """
            UPDATE tasks
            SET
                progress = %s,
                status = %s,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = %s
            """,
            (
                task_progress,
                data.status,
                task_id
            )
        )

        # =================================================
        # COMMIT
        # =================================================

        connection.commit()
 # =================================================
# CRM NOTIFICATION TO EMPLOYEE
# =================================================

        try:

          notification_title = "Task Completed"

          if data.status == "Rework":
           notification_title = "Task Sent for Rework"

          elif data.status == "In Review":
           notification_title = "Task Review Updated"

          if data.status == "Completed":

           notification_message = (
              f"Your task '{task['title']}' has been completed."
            )

          elif data.status == "Rework":

           notification_message = (
            f"Your task '{task['title']}' has been sent for rework."
          )

          else:

           notification_message = (
            f"Your task '{task['title']}' review has been updated."
        )

          create_crm_notification(
          employee_id=submission["employee_id"],
          title=notification_title,
          message=notification_message,
          notification_type="task_review"
          )

        except Exception as notification_error:

         print(
         "TASK REVIEW CRM NOTIFICATION ERROR:",
          str(notification_error)
         )


# =================================================
# GET FINAL RATING
# =================================================

        cursor.execute(
            """
            SELECT
                manager_feedback,
                task_rating,
                status
            FROM task_submissions
            WHERE id = %s
            """,
            (submission["id"],)
        )

        updated_submission = cursor.fetchone()

        final_rating = (
            updated_submission.get("task_rating")
            if updated_submission
            else data.task_rating
        )

        final_feedback = (
            updated_submission.get("manager_feedback")
            if updated_submission
            else data.manager_feedback.strip()
        )

        # =================================================
        # RESPONSE
        # =================================================

        return {

            "status": "success",

            "message": (
                "Task approved successfully."
                if data.status == "Completed"

                else
                "Task sent for rework successfully."
                if data.status == "Rework"

                else
                "Review updated successfully."
            ),

            "task_id": task_id,

            "submission_id": submission["id"],

            "employee_id": submission["employee_id"],

            "progress": task_progress,

            "task_status": data.status,

            "manager_feedback": final_feedback or "",

            "task_rating": final_rating

        }

    except HTTPException:

        connection.rollback()
        raise

    except Exception as e:

        connection.rollback()

        print(
            "MANAGER REVIEW ERROR:",
            str(e)
        )

        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

    finally:

        cursor.close()
        connection.close()

# =========================================================
# UPDATE TASK STATUS
# =========================================================

@router.put("/{task_id}/status")
def update_task_status(
    task_id: int,
    data: TaskStatusUpdate = Body(...)
):

    allowed_statuses = [
        "Pending",
        "In Progress",
        "In Review",
        "Completed"
    ]

    if data.status not in allowed_statuses:

        raise HTTPException(
            status_code=400,
            detail=(
                "Invalid status. "
                "Allowed: Pending, In Progress, "
                "In Review, Completed"
            )
        )

    connection = get_connection()
    cursor = connection.cursor()

    try:

        cursor.execute(
            """
            SELECT id
            FROM tasks
            WHERE id = %s
            """,
            (task_id,)
        )

        task = cursor.fetchone()

        if not task:

            raise HTTPException(
                status_code=404,
                detail="Task not found"
            )

        cursor.execute(
            """
            UPDATE tasks
            SET
                status = %s,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = %s
            """,
            (
                data.status,
                task_id
            )
        )

        connection.commit()

        return {
            "status": "success",
            "message": "Task status updated successfully.",
            "task_id": task_id,
            "task_status": data.status
        }

    except HTTPException:

        connection.rollback()
        raise

    except Exception as e:

        connection.rollback()

        print(
            "UPDATE STATUS ERROR:",
            str(e)
        )

        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

    finally:

        cursor.close()
        connection.close()


# =========================================================
# DELETE TASK
# =========================================================

@router.delete("/{task_id}")
def delete_task(task_id: int):

    connection = get_connection()
    cursor = connection.cursor()

    try:

        cursor.execute(
            """
            SELECT id
            FROM tasks
            WHERE id = %s
            """,
            (task_id,)
        )

        task = cursor.fetchone()

        if not task:

            raise HTTPException(
                status_code=404,
                detail="Task not found"
            )

        cursor.execute(
            """
            DELETE FROM tasks
            WHERE id = %s
            """,
            (task_id,)
        )

        connection.commit()

        return {
            "status": "success",
            "message": "Task deleted successfully.",
            "task_id": task_id
        }

    except HTTPException:

        connection.rollback()
        raise

    except Exception as e:

        connection.rollback()

        print(
            "DELETE TASK ERROR:",
            str(e)
        )

        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

    finally:

        cursor.close()
        connection.close()