import os
from datetime import date, datetime
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks, Path, Form,File,UploadFile
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
from typing import List, Optional

from app.db import database
from ...models.platform.workforcemodel import (
    Workforce, WorkforceBase, WorkforceResponseList, WorkforceUpdate
)
from ...dependencies.auth import get_current_userdetails
from ...libraries.object import str_to_objectid

# Import service functions
from ...services.platform.workforce import (
    create_workforce_service,
    get_workforce_service,
    read_workforce_service,
    update_workforce_service,
    delete_workforce_service,
)

router = APIRouter()

def parse_date(date_str: str) -> date:  # Now 'date' is recognized
    try:
        if "T" in date_str:
            return datetime.fromisoformat(date_str.replace("Z", "")).date()
        return datetime.strptime(date_str, "%Y-%m-%d").date()
    except (ValueError, AttributeError) as e:
        raise ValueError(f"Invalid date format: {date_str}")

@router.post("/", response_model=Workforce)
async def create_workforce_endpoint(
    # Existing required fields
    first_name: str = Form(...),
    last_name: str = Form(...),
    mobile_number: str = Form(...),
    email_id: str = Form(...),
    workforce_category_id: str = Form(...),
    gender: str = Form(...),
    date_of_birth: str = Form(...),
    join_date: str = Form(...),
    photo: UploadFile = File(None),
    
    # Optional fields with explicit None handling
    license_id: Optional[str] = Form(None),
    national_id: Optional[str] = Form(None),
    emergency_contact: Optional[str] = Form(None),
    shift_timing: Optional[str] = Form(None),
    address: Optional[str] = Form(None),
    blood_group: Optional[str] = Form(None),
    is_human: Optional[bool] = Form(True),
    skills: Optional[str] = Form(None),  # Accepts JSON string for skills list
    certifications: Optional[str] = Form(None),
    workforce_category_name: str = Form(...),
    skills_name: str = Form(...),
    
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    # Create upload directory
    os.makedirs("public/workforce", exist_ok=True)
    
    # Handle photo upload
    photo_filename = None
    if photo and photo.filename:
        timestamp = int(datetime.now().timestamp())
        ext = photo.filename.split('.')[-1]
        photo_filename = f"workforce-{timestamp}.{ext}"
        filepath = f"public/workforce/{photo_filename}"
        
        with open(filepath, "wb") as buffer:
            content = await photo.read()
            buffer.write(content)

    try:
        # Use parse_date instead of duplicating logic
        dob_date = parse_date(date_of_birth)
        join_date_obj = parse_date(join_date)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

    # Parse the skills string into a Python list
    parsed_skills = []
    if skills:
        try:
            parsed_skills = json.loads(skills)
        except json.JSONDecodeError:
            raise HTTPException(status_code=400, detail="Invalid JSON in 'skills' field")

    # Parse the certifications string into a Python list
    parsed_certifications = []
    if certifications:
        try:
            parsed_certifications = json.loads(certifications)
            if not isinstance(parsed_certifications, list):
                raise ValueError
        except (json.JSONDecodeError, ValueError):
            raise HTTPException(status_code=400, detail="Invalid JSON in 'certifications' field")

    workforce_data = {
        "first_name": first_name,
        "last_name": last_name,
        "mobile_number": mobile_number,
        "email_id": email_id,
        "workforce_category_id": workforce_category_id,
        "gender": gender,
        "date_of_birth": dob_date,
        "join_date": join_date_obj,
        "photo": photo_filename,
        "account_id": current_user.get("account_id"),
        "user_id": str(current_user["_id"]),
        # Add optional fields
        "license_id": license_id or None,
        "national_id": national_id or None,
        "emergency_contact": emergency_contact or None,
        "shift_timing": shift_timing or None,
        "address": address,
        "blood_group": blood_group,
        "is_human": is_human,
        "skills": parsed_skills,
        "certifications": parsed_certifications,
        "workforce_category_name": workforce_category_name,
        "skills_name": skills_name,
    }

    try:
        result = create_workforce_service(WorkforceBase(**workforce_data), db)
        return JSONResponse(content=jsonable_encoder(result))
    except HTTPException as he:
        raise he
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/list/", response_model=WorkforceResponseList)
def get_workforce(
    skip: int = 0,
    limit: int = 10,
    q: Optional[str] = None,
    status: Optional[str] = None,
    join_date_from: Optional[str] = None,
    join_date_to: Optional[str] = None,
    sort_by: Optional[str] = None,         
    sort_order: Optional[str] = "asc",
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    """
    Returns a list of workforce entries
    """
    return get_workforce_service(skip, limit, q, status, join_date_from, join_date_to, sort_by, sort_order, db, current_user)

@router.get("/{workforce_id}", response_model=Workforce)
def read_workforce(
    workforce_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    """
    Returns workforce details by ID
    """
    workforce = read_workforce_service(workforce_id, db)
    if workforce is None:
        raise HTTPException(status_code=404, detail="Workforce not found")
    return workforce

@router.put("/{workforce_id}", response_model=Workforce)
def update_workforce(
    workforce_id: str,
    workforce_data: WorkforceUpdate,
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    """
    Updates workforce information
    """
    updated_workforce = update_workforce_service(workforce_id, workforce_data, db)
    if updated_workforce is None:
        raise HTTPException(status_code=404, detail="Workforce not found after update")
    return updated_workforce

@router.delete("/{workforce_id}", response_model=Workforce)
def delete_workforce(
    workforce_id: str = Path(..., description="The ID of the workforce entry"),
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    """
    Deletes a workforce entry by ID
    """
    workforce = delete_workforce_service(workforce_id, db)
    if workforce is None:
        raise HTTPException(status_code=404, detail="Workforce not found")
    return workforce