# ============================================================
# Shared helpers for the Recruitment API (additive, new file)
# ============================================================
from datetime import date, datetime
from decimal import Decimal, InvalidOperation

from django.db import transaction
from django.utils import timezone
from django.utils.dateparse import parse_date, parse_datetime
from rest_framework import status as http
from rest_framework.decorators import action
from rest_framework.permissions import BasePermission
from rest_framework.response import Response

from Employee.employee_crud_permissions import (
    AdminOrEmployeeJWTAuthentication,
    _role_is_usable,
    actor_label,
    resolve_actor_role,
    resolve_company_for_user,
    role_allows,
)
from Employee.models import EmployeeDT

from .models import STAGE_CODES, StageHistory, CandidateProfile
from django.db.models import Q

# ---------------------------------------------------------------
# responses (same envelope as Company/hr_api_views.py)
# ---------------------------------------------------------------
def ok(code, message, data=None, status=http.HTTP_200_OK, **extra):
    body = {"status": "success", "code": code, "message": message, "data": data}
    body.update(extra)
    return Response(body, status=status)


def err(code, message, status=http.HTTP_400_BAD_REQUEST, errors=None):
    body = {"status": "error", "code": code, "message": message, "data": None}
    if errors is not None:
        body["errors"] = errors
    return Response(body, status=status)


# ---------------------------------------------------------------
# permission: Company Admin always; employee only through role
# checkboxes. Looks at can_<action>_recruitment first, and falls
# back to the existing can_<action>_employees flags so current HR
# roles work without touching EmployeeRole.
# ---------------------------------------------------------------
def recruitment_allows(user, action):
    actor = resolve_actor_role(user)
    if actor == "admin":
        return True
    if actor is None:
        return False
    role = _role_is_usable(user)
    if role is None:
        return False
    fallback = "edit" if action == "approve" else action
    if role_allows(role, "recruitment", fallback):
        return True
    return role_allows(role, "employees", fallback)


class IsRecruitmentUser(BasePermission):
    message = "You do not have permission to use the Recruitment module."

    METHOD_ACTION = {"GET": "view", "HEAD": "view", "OPTIONS": "view",
                     "POST": "create", "PUT": "edit", "PATCH": "edit",
                     "DELETE": "delete"}

    def has_permission(self, request, view):
        action = getattr(view, "permission_action", None)
        if action is None and getattr(view, "action", None) == "update_post":
            action = "edit"
        if action is None and getattr(view, "action", None) == "delete_post":
            action = "delete"
        if action is None:
            view_action = getattr(view, "action", None)
            action = (getattr(view, "permission_action_map", None) or {}).get(view_action)
        if action is None:
            action = self.METHOD_ACTION.get(request.method)
        if action is None:
            return False
        return recruitment_allows(request.user, action)


class IsAnyEmployee(BasePermission):
    """For interviewer / hiring-manager self-service endpoints."""
    message = "Employee login required."

    def has_permission(self, request, view):
        return isinstance(request.user, EmployeeDT)


class RecruitmentAuthMixin:
    authentication_classes = [AdminOrEmployeeJWTAuthentication]
    permission_classes = [IsRecruitmentUser]

    # -- POST-only clients (same convention as the existing Employee API: delete via POST) --
    @action(detail=True, methods=["post"], url_path="update")
    def update_post(self, request, pk=None):
        fn = getattr(self, "partial_update", None)
        if fn is None:
            return err("NOT_ALLOWED", "Update is not supported here.", http.HTTP_405_METHOD_NOT_ALLOWED)
        return fn(request, pk)

    @action(detail=True, methods=["post"], url_path="delete")
    def delete_post(self, request, pk=None):
        fn = getattr(self, "destroy", None)
        if fn is None:
            return err("NOT_ALLOWED", "Delete is not supported here.", http.HTTP_405_METHOD_NOT_ALLOWED)
        return fn(request, pk)

    def company(self):
        return resolve_company_for_user(self.request.user)

    def actor(self):
        return actor_label(self.request.user)


# ---------------------------------------------------------------
# parsing helpers
# ---------------------------------------------------------------
def to_decimal(value, default=None):
    if value in (None, ""):
        return default
    try:
        return Decimal(str(value))
    except (InvalidOperation, ValueError):
        raise ValueError(f"Invalid number: {value}")


def to_date(value):
    if value in (None, ""):
        return None
    if isinstance(value, date):
        return value
    d = parse_date(str(value))
    if d is None:
        raise ValueError(f"Invalid date (use YYYY-MM-DD): {value}")
    return d


def to_datetime(value):
    if value in (None, ""):
        return None
    dt = parse_datetime(str(value))
    if dt is None:
        d = parse_date(str(value))
        if d is None:
            raise ValueError(f"Invalid datetime (use ISO 8601): {value}")
        dt = datetime(d.year, d.month, d.day, 9, 0)
    if timezone.is_naive(dt):
        dt = timezone.make_aware(dt)
    return dt


def to_bool(value, default=False):
    if value is None:
        return default
    return str(value).strip().lower() in ("1", "true", "yes", "y", "on")


def to_list(value):
    if value in (None, ""):
        return []
    if isinstance(value, (list, tuple)):
        return [str(v).strip() for v in value if str(v).strip()]
    return [v.strip() for v in str(value).split(",") if v.strip()]


def lpa(value):
    return float(value) if value is not None else None


def next_seq(model, company, field, prefix, width=3, start=1):
    """PREFIX-<n> style sequence per company, e.g. REQ-2026-001."""
    last = (model.objects.filter(company=company, **{f"{field}__startswith": prefix})
            .order_by("-id").values_list(field, flat=True).first())
    n = start
    if last:
        try:
            n = int(last.rsplit("-", 1)[1]) + 1
        except (IndexError, ValueError):
            n = model.objects.filter(company=company).count() + start
    return f"{prefix}{str(n).zfill(width)}"


# ---------------------------------------------------------------
# employee connections
# ---------------------------------------------------------------
def employee_by_code(company, code):
    """Resolve an employee (hiring manager / interviewer / recruiter /
    reporting manager) from employee_code, company-isolated."""
    if code in (None, ""):
        return None
    emp = EmployeeDT.objects.filter(company=company, employee_code=str(code).strip()).first()
    if emp is None:
        raise ValueError(f"Employee '{code}' not found in your company.")
    return emp

# ADDITIVE: "Only Hiring Manager" - the eligible roles now come from settings.
# Default = Hiring Manager only. To also allow HR Managers, set in settings.py:
#   HIRING_MANAGER_ROLE_CODES = ("hiring_manager", "hr_manager")
#   HIRING_MANAGER_ROLE_NAMES = ("hiring manager", "hr manager")
from django.conf import settings as _settings
HIRING_MANAGER_ROLE_CODES = {str(x).lower() for x in getattr(_settings, "HIRING_MANAGER_ROLE_CODES", ("hiring_manager",))}
HIRING_MANAGER_ROLE_NAMES = {str(x).lower() for x in getattr(_settings, "HIRING_MANAGER_ROLE_NAMES", ("hiring manager",))}



def hiring_manager_qs(company):
    """Active employees whose account role is HR Manager / Hiring Manager."""
    q = Q()
    for c in HIRING_MANAGER_ROLE_CODES:
        q |= Q(account__role__role_code__iexact=c)
    for n in HIRING_MANAGER_ROLE_NAMES:
        q |= Q(account__role__role_name__iexact=n)
    return EmployeeDT.objects.filter(company=company, is_active=True).filter(q).select_related("account__role")


def hiring_manager_by_code(company, code):
    if code in (None, ""):
        return None
    emp = hiring_manager_qs(company).filter(employee_code=str(code).strip()).first()
    if emp is None:
        raise ValueError(f"Employee '{code}' is not an eligible Hiring Manager (HR) in your company.")
    return emp


def emp_brief(emp, request=None):
    if emp is None:
        return None
    img = None
    f = getattr(emp, "profile_image", None) or getattr(emp, "image", None)
    if f:
        try:
            img = request.build_absolute_uri(f.url) if request else f.url
        except Exception:
            img = None
    return {
        "employee_code": emp.employee_code,
        "name": emp.name,
        "email": emp.email,
        "designation": getattr(emp, "Designation", None),
        "department": (emp.department.name if getattr(emp, "department_id", None)
                       else getattr(emp, "Department", None)),
        "profile_image": img,
    }


def candidates_qs(company):
    """
    Candidates = EmployeeDT rows that are part of hiring: they either
    have a CandidateProfile, or were created by the existing 8-step
    candidate form (applied_position filled). NOTE: every EmployeeDT
    gets a candidate_id on save, so candidate_id alone cannot be used.
    """
    from django.db.models import Q
    return EmployeeDT.objects.filter(company=company).filter(
        Q(recruitment_profile__isnull=False)
        | Q(Employee_Status="Candidate")
        | (Q(applied_position__isnull=False) & ~Q(applied_position=""))
    )


def candidate_by_ref(company, ref):
    """Candidate by DB id OR by candidate_id code (e.g. CAN-301)."""
    from django.db.models import Q
    if ref in (None, ""):
        return None
    q = Q(candidate_id=str(ref).strip())
    if str(ref).strip().isdigit():
        q |= Q(pk=int(str(ref).strip()))
    return candidates_qs(company).filter(q).first()


def get_profile(candidate, company=None, create=True):
    prof = getattr(candidate, "recruitment_profile", None) if candidate.pk else None
    try:
        prof = candidate.recruitment_profile
    except CandidateProfile.DoesNotExist:
        prof = None
    if prof is None and create:
        prof = CandidateProfile.objects.create(company=company or candidate.company, candidate=candidate)
    return prof


def candidate_brief(c, request=None):
    prof = get_profile(c, create=False)
    return {
        "id": c.id,
        "candidate_id": c.candidate_id,
        "name": c.name,
        "email": c.email,
        "phone_number": c.phone_number,
        "applied_position": c.applied_position,
        "stage": c.candidate_status,
        "profile_image": (request.build_absolute_uri(c.profile_image.url)
                          if request and getattr(c, "profile_image", None) else None),
        "requisition_id": (prof.requisition.requisition_id if prof and prof.requisition_id else None),
    }


# ---------------------------------------------------------------
# stage engine (keeps EmployeeDT.candidate_status as the single
# source of truth and writes an audit trail)
# ---------------------------------------------------------------
@transaction.atomic
def set_stage(candidate, new_stage, actor=None, note=None, only_forward_from=None):
    new_stage = (new_stage or "").strip().upper()
    if new_stage not in STAGE_CODES:
        raise ValueError(f"Invalid stage '{new_stage}'. Allowed: {', '.join(STAGE_CODES)}")
    old = (candidate.candidate_status or "").upper() or None
    if old == new_stage:
        return candidate
    if only_forward_from is not None and old not in only_forward_from:
        return candidate
    candidate.candidate_status = new_stage
    candidate.save(update_fields=["candidate_status"])
    prof = get_profile(candidate)
    prof.stage_changed_at = timezone.now()
    prof.updated_by = actor
    prof.save(update_fields=["stage_changed_at", "updated_by", "updated_at"])
    StageHistory.objects.create(company=candidate.company, candidate=candidate,
                                from_stage=old, to_stage=new_stage, note=note, changed_by=actor)
    return candidate


def stage_label(code):
    from .models import STAGES
    return dict(STAGES).get((code or "").upper(), code)

