# jobs.py (implementation)
from datetime import datetime
from fastapi import APIRouter, HTTPException, Depends, Request, Form, File, UploadFile
from typing import Optional, List
from app.db import database
from app.v1.models.platform.jobs import JobBase, JobCreate, JobUpdate, JobRead
from app.v1.models.saas.usersmodel import User
from app.v1.dependencies.auth import get_current_userdetails
import json

router = APIRouter()

COLLECTION_NAME = "jobs"
BASE_URL = "http://localhost:8003"

@router.post("/", response_model=JobRead)
async def create_job(
    job_data: JobCreate,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Create a new job
    """
    job_data_dict = job_data.dict()
    job_data_dict["account_id"] = current_user.get("account_id")
    job_data_dict["created_date"] = datetime.utcnow()
    job_data_dict["status"] = "pending"
    
    jobs_collection = db[COLLECTION_NAME]
    try:
        result = jobs_collection.insert_one(job_data_dict)
        job_data_dict["job_id"] = str(result.inserted_id)
        return job_data_dict
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Error creating job: {str(e)}")

@router.get("/", response_model=List[JobRead])
def get_jobs(
    skip: int = 0,
    limit: int = 10,
    q: Optional[str] = None,
    status: Optional[str] = None,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Get list of jobs with pagination
    """
    query = {"account_id": current_user.get("account_id")}
    
    if status:
        query["status"] = status
    if q:
        regex_query = {"$regex": q, "$options": "i"}
        query["$or"] = [
            {"service_id": regex_query},
            {"customer_id": regex_query},
            {"status": regex_query}
        ]
    
    jobs_collection = db[COLLECTION_NAME]
    jobs_cursor = jobs_collection.find(query).skip(skip).limit(limit)
    
    jobs_list = []
    for job in jobs_cursor:
        job["job_id"] = str(job["_id"])
        jobs_list.append(job)
    
    return jobs_list

@router.get("/{job_id}", response_model=JobRead)
def get_job(
    job_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Get a specific job by ID
    """
    jobs_collection = db[COLLECTION_NAME]
    job = jobs_collection.find_one({"_id": database.str_to_objectid(job_id)})
    
    if not job:
        raise HTTPException(status_code=404, detail="Job not found")
    
    if job.get("account_id") != current_user.get("account_id"):
        raise HTTPException(status_code=403, detail="Not authorized to access this job")
    
    job["job_id"] = str(job["_id"])
    return job

@router.put("/{job_id}", response_model=JobRead)
def update_job(
    job_id: str,
    job_update: JobUpdate,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Update a job
    """
    jobs_collection = db[COLLECTION_NAME]
    
    # Check if job exists and belongs to user's account
    existing_job = jobs_collection.find_one({"_id": database.str_to_objectid(job_id)})
    if not existing_job:
        raise HTTPException(status_code=404, detail="Job not found")
    
    if existing_job.get("account_id") != current_user.get("account_id"):
        raise HTTPException(status_code=403, detail="Not authorized to update this job")
    
    # Prepare update data
    update_data = job_update.dict(exclude_unset=True)
    update_data["updated_date"] = datetime.utcnow()
    
    # Perform update
    result = jobs_collection.update_one(
        {"_id": database.str_to_objectid(job_id)},
        {"$set": update_data}
    )
    
    if result.modified_count == 0:
        raise HTTPException(status_code=400, detail="No changes made to the job")
    
    # Return updated job
    updated_job = jobs_collection.find_one({"_id": database.str_to_objectid(job_id)})
    updated_job["job_id"] = str(updated_job["_id"])
    return updated_job

@router.delete("/{job_id}", response_model=JobRead)
def delete_job(
    job_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Delete a job
    """
    jobs_collection = db[COLLECTION_NAME]
    
    # Check if job exists and belongs to user's account
    job = jobs_collection.find_one({"_id": database.str_to_objectid(job_id)})
    if not job:
        raise HTTPException(status_code=404, detail="Job not found")
    
    if job.get("account_id") != current_user.get("account_id"):
        raise HTTPException(status_code=403, detail="Not authorized to delete this job")
    
    # Delete job
    jobs_collection.delete_one({"_id": database.str_to_objectid(job_id)})
    
    job["job_id"] = str(job["_id"])
    return job

@router.get("/account/{account_id}", response_model=List[JobRead])
def get_jobs_by_account(
    account_id: str,
    skip: int = 0,
    limit: int = 10,
    status: Optional[str] = None,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Get jobs by account ID (with permission check)
    """
    # Check if current user has access to this account
    if account_id != current_user.get("account_id") and current_user.get("roles") != 1:
        raise HTTPException(status_code=403, detail="Not authorized to view jobs for this account")
    
    query = {"account_id": account_id}
    if status:
        query["status"] = status
    
    jobs_collection = db[COLLECTION_NAME]
    jobs_cursor = jobs_collection.find(query).skip(skip).limit(limit)
    
    jobs_list = []
    for job in jobs_cursor:
        job["job_id"] = str(job["_id"])
        jobs_list.append(job)
    
    return jobs_list

@router.post("/{job_id}/status", response_model=JobRead)
def update_job_status(
    job_id: str,
    status: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Update job status
    """
    jobs_collection = db[COLLECTION_NAME]
    
    # Check if job exists and belongs to user's account
    job = jobs_collection.find_one({"_id": database.str_to_objectid(job_id)})
    if not job:
        raise HTTPException(status_code=404, detail="Job not found")
    
    if job.get("account_id") != current_user.get("account_id"):
        raise HTTPException(status_code=403, detail="Not authorized to update this job")
    
    # Update status
    update_data = {
        "status": status,
        "updated_date": datetime.utcnow()
    }
    
    if status == "active" and not job.get("actual_start"):
        update_data["actual_start"] = datetime.utcnow()
    elif status == "completed" and not job.get("actual_end"):
        update_data["actual_end"] = datetime.utcnow()
    
    result = jobs_collection.update_one(
        {"_id": database.str_to_objectid(job_id)},
        {"$set": update_data}
    )
    
    if result.modified_count == 0:
        raise HTTPException(status_code=400, detail="Failed to update job status")
    
    # Return updated job
    updated_job = jobs_collection.find_one({"_id": database.str_to_objectid(job_id)})
    updated_job["job_id"] = str(updated_job["_id"])
    return updated_job