import os
from datetime import date, datetime
import json
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks, Path, Form,File,UploadFile, Query
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
from typing import List, Optional, Dict, Any

from ...models.saas.usersmodel import (UserBase,EmailAction)

from app.db import database
from ...models.platform.workforcemodel import (
    Workforce, WorkforceBase, WorkforceResponseList, WorkforceUpdate,WorkforceDetailsRequest,WorkforceResponse,TagNameResponse
)
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,
    get_workforce_list_by_type,
    get_workforce_details_with_tasks_and_schedules
)

from ...services.saas.users import (
    create_user_service,send_email_verification_service,read_user_serviceby_email
)

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
    background_tasks: BackgroundTasks, 
    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 "1,2", "[1,2]" or "5"
    certifications: Optional[str] = Form(None),
    workforce_category_name: str = Form(...),
    skills_name: str = Form(...),
    tag_name: Optional[str] = Form(None),
    addons_name: Optional[str] = Form(None),
    
    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")

    # ---- SKILLS PARSING (FINAL FIX) ----
    parsed_skills = []

    if skills is not None:
        s = str(skills).strip()

        # Case 1: JSON array → "[1,2]"
        if s.startswith("[") and s.endswith("]"):
            try:
                parsed_skills = [int(x) for x in json.loads(s)]
            except Exception:
                raise HTTPException(status_code=400, detail="Invalid skills JSON array")

        # Case 2: comma-separated values → "1,2,3"
        elif "," in s:
            parsed_skills = [
                int(x.strip()) for x in s.split(",") if x.strip().isdigit()
            ]

        # Case 3: single integer → "5"
        elif s.isdigit():
            parsed_skills = [int(s)]

        # Invalid format
        else:
            raise HTTPException(
                status_code=400,
                detail="Skills must be comma-separated or JSON array"
            )

    # 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,
        "tag_name": tag_name,
        "addons_name": addons_name,
        "is_fleet_assigned": False
    }

    try:
        result = create_workforce_service(WorkforceBase(**workforce_data), db)
        workforce_id = result["_id"]
        # Construct user login data
        default_password = "Ssk@44140065"

        
        # Create login user
        email_action = {
            "emails": email_id,
            "action": "signup",
            "account_id": current_user.get("account_id"),
            "role": 103  # Match `user["roles"]`
        } 
        email_action_model = EmailAction(**email_action)
        resemailvers = send_email_verification_service(email_action_model, background_tasks, db)

        resVerificationCode = read_user_serviceby_email(email_id, db);
        print("send_email_verification_servicesend_email_verification_service")        
        print(resVerificationCode)
        verification_code_res = resVerificationCode.get("verificationCode")
        print(verification_code_res)
        print("==============================================================")

        user = {
            "email": email_id,
            "password": "Default@123",
            "verificationCode": verification_code_res,
            "name": f"{first_name} {last_name}",
            "mobile": mobile_number,
            "account_id": current_user.get("account_id"),
            "date_of_birth": dob_date,
            "google_connect": "",
            "linkedin_connect": "",
            "token": "",
            "picurl": photo_filename or "",
            "is_active": True,
            "is_verified": True,
            "mobile_verified": False,
            "roles": 103,
            "workforce_id": workforce_id,
        }
        print("useruseruseruseruser149149149149149149149149")
        print(user)
        print("============================================")
        user_model = UserBase(**user)
        resultUser = create_user_service(user_model, background_tasks, 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",
    account_id: Optional[str] = None,
    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, account_id, 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

@router.get("/dropdown/workforce", response_model=List[Dict[str, str]])
async def get_workforce_dropdown_list(
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails),
    q: str = Query(default="", description="Search query for workforce name")
):
    account_id = current_user["account_id"]
    return get_workforce_dropdown_list(db, account_id, q)

# @router.get("/freeworkforce/{workforce_id}", response_model=List[Dict[str, object]])
# async def get_freeworkforce_list(
#     db: database.MongoDB = Depends(database.get_mongo_db),
#     current_user: dict = Depends(get_current_userdetails),
#     q: str = Query(default="", description="Search query for workforce name")
# ):
#     account_id = current_user["account_id"]
#     return get_freeworkforce_with_counts(db, account_id, q)

@router.get("/freeworkforce/{workforce_id}", response_model=List[Dict[str, object]])
async def get_workforce_list(
    customer_id: Optional[str],
    type: str = Query(..., description="Type of workforce: free or scheduled"),
    q: str = Query(default="", description="Search query for workforce name"),
    skills: Optional[List[str]] = Query(default=None, description="Skill IDs to filter workforce"),
    vehicle_required: Optional[bool] = Query(default=None, description="True = mapped (assigned), False = unmapped (not assigned)"),
    can_fly: Optional[bool] = Query(default=None, description="Filter by can_fly true/false"),
    addons_name: Optional[str] = Query(default=None, description="Filter by addons name"),
    vehicle_model_id: Optional[str] = Query(default=None, description="Filter by model name"),
    start_time: Optional[datetime] = Query(default=None, description="Task start time (ISO format)"),
    end_time: Optional[datetime] = Query(default=None, description="Task end time (ISO format)"),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    account_id = current_user["account_id"]
    print("COMING FREE WQORKFORCE 2767276")
    if type not in ["free", "scheduled"]:
        raise HTTPException(status_code=400, detail="Invalid type. Use 'free' or 'scheduled'.")

    return get_workforce_list_by_type(db, account_id, type, q, skills, vehicle_required, can_fly, addons_name, vehicle_model_id, start_time, end_time, customer_id)

@router.post("/details", response_model=List[Dict[str, Any]])
async def get_workforce_schedule_task_details(
    payload: WorkforceDetailsRequest,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    account_id = current_user["account_id"]
    result = await get_workforce_details_with_tasks_and_schedules(
        db=db,
        account_id=account_id,
        workforce_id=payload.workforce_id
    )
    return result

# @router.get("/workforce/details", response_model=List[Dict[str, Any]])
# async def get_workforce_schedule_task_details(
#     db: database.MongoDB = Depends(database.get_mongo_db),
#     current_user: dict = Depends(get_current_userdetails)
# ):
#     account_id = current_user["account_id"]
#     return await get_workforce_details_with_tasks_and_schedules(db, account_id)

@router.get(
    "/allwithstatus",
    response_model=List[WorkforceResponse],
    tags=["Workforce"]
)
async def get_all_workforce_with_status(
    q: str = Query(default="", description="Search query for workforce name"),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    account_id = current_user["account_id"]
    return workforce_service.get_workforce_list_with_status(db, account_id, q)

@router.get("/tags", response_model=List[TagNameResponse], tags=["Workforce"])
async def get_tag_names(
    q: str = Query(default="", description="Search query for tag name"),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    """
    Returns the list of tag names (supports search with `q`)
    """
    return workforce_service.get_tag_name_list(db, q)
