
# ============================================================
# Recruitment/admin.py
# COMPLETE ADDITIVE ADMIN CONFIGURATION
#
# Includes:
# 1. JobRequisition
# 2. JobDescription
# 3. CandidateProfile
# 4. StageHistory
# 5. InterviewRound
# 6. InterviewFeedback
# 7. CandidateSelection
# 8. Offer
# 9. DocumentReview
# 10. BGVCase
# 11. CandidateApproval
# 12. HikeApproval
# 13. IdentityVerification
# 14. HiringChecklistItem
# 15. HiringQuestion
# 16. InterviewerAssignment
# 17. DocumentUploadLink
# 18. RequisitionRoles
# 19. CandidatePortalLink
# 20. CandidatePortalActivity
# 21. CandidatePortalAccount
# 22. CandidatePortalDraft
#
# Existing Company / Employee / SuperAdmin admin.py files
# are not modified.
# ============================================================

from django.contrib import admin
from django.contrib.auth.hashers import make_password, identify_hasher

from .models import (
    BGVCase,
    CandidateProfile,
    CandidateSelection,
    DocumentReview,
    InterviewFeedback,
    InterviewRound,
    JobDescription,
    JobRequisition,
    Offer,
    StageHistory,
)

from .models_plus import (
    CandidateApproval,
    HikeApproval,
    IdentityVerification,
    HiringChecklistItem,
    HiringQuestion,
    InterviewerAssignment,
    DocumentUploadLink,
    RequisitionRoles,
)

from .models_portal import (
    CandidatePortalLink,
    CandidatePortalActivity,
)

# CandidatePortalAccount and CandidatePortalDraft are defined
# in the additive candidate portal models module.
# Change this import only if you placed these classes elsewhere.
from .models import CandidatePortalAccount, CandidatePortalDraft


# ============================================================
# COMMON TRACKING CONFIGURATION
# ============================================================

TRACKING = ("created_by", "updated_by", "id_version")
TIMESTAMPS = ("created_at", "updated_at")


class TrackedAdmin(admin.ModelAdmin):
    """Base admin for models that support audit tracking."""

    list_per_page = 25
    save_on_top = True
    actions = ["mark_active", "mark_inactive"]

    def get_readonly_fields(self, request, obj=None):
        names = {field.name for field in self.model._meta.get_fields()}

        auto_fields = [
            field
            for field in TRACKING + TIMESTAMPS
            if field in names
        ]

        existing = list(super().get_readonly_fields(request, obj))

        return list(dict.fromkeys(existing + auto_fields))

    def save_model(self, request, obj, form, change):
        who = f"admin:{request.user.pk}"

        if not change and hasattr(obj, "created_by"):
            if not getattr(obj, "created_by", None):
                obj.created_by = who

        if hasattr(obj, "updated_by"):
            obj.updated_by = who

        super().save_model(request, obj, form, change)

    @admin.action(description="Mark selected records ACTIVE")
    def mark_active(self, request, queryset):
        count = 0

        for obj in queryset:
            if hasattr(obj, "is_active"):
                obj.is_active = True

                if hasattr(obj, "updated_by"):
                    obj.updated_by = f"admin:{request.user.pk}"

                obj.save()
                count += 1

        self.message_user(
            request,
            f"{count} record(s) activated."
        )

    @admin.action(description="Mark selected records INACTIVE")
    def mark_inactive(self, request, queryset):
        count = 0

        for obj in queryset:
            if hasattr(obj, "is_active"):
                obj.is_active = False

                if hasattr(obj, "updated_by"):
                    obj.updated_by = f"admin:{request.user.pk}"

                obj.save()
                count += 1

        self.message_user(
            request,
            f"{count} record(s) deactivated."
        )


# ============================================================
# 1. JOB DESCRIPTION INLINE
# ============================================================

class JobDescriptionInline(admin.StackedInline):
    model = JobDescription
    extra = 0
    can_delete = False

    fields = (
        "jd_code",
        "company",
        "experience_min_years",
        "experience_max_years",
        "required_skills",
        "responsibilities",
        "qualifications",
        "is_published",
        "published_at",
    )


# ============================================================
# 2. JOB REQUISITION
# ============================================================

@admin.register(JobRequisition)
class JobRequisitionAdmin(TrackedAdmin):

    list_display = (
        "requisition_id",
        "position_title",
        "company",
        "department_name",
        "vacancies",
        "priority",
        "approval_status",
        "hiring_manager",
        "is_active",
        "created_at",
    )

    list_filter = (
        "approval_status",
        "priority",
        "work_mode",
        "is_active",
        "company",
    )

    search_fields = (
        "requisition_id",
        "position_title",
        "department_name",
        "location",
        "hiring_manager__name",
        "hiring_manager__employee_code",
    )

    raw_id_fields = (
        "company",
        "department",
        "hiring_manager",
    )

    date_hierarchy = None
    inlines = [JobDescriptionInline]


# ============================================================
# 3. JOB DESCRIPTION
# ============================================================

@admin.register(JobDescription)
class JobDescriptionAdmin(TrackedAdmin):

    list_display = (
        "jd_code",
        "requisition",
        "company",
        "experience_min_years",
        "experience_max_years",
        "is_published",
        "is_active",
    )

    list_filter = (
        "is_published",
        "is_active",
        "company",
    )

    search_fields = (
        "jd_code",
        "requisition__requisition_id",
        "requisition__position_title",
    )

    raw_id_fields = (
        "company",
        "requisition",
    )


# ============================================================
# 4. CANDIDATE PROFILE
# ============================================================

@admin.register(CandidateProfile)
class CandidateProfileAdmin(TrackedAdmin):

    list_display = (
        "candidate",
        "company",
        "requisition",
        "current_company",
        "total_experience_years",
        "notice_period_days",
        "priority",
        "recruiter",
        "stage_changed_at",
        "is_active",
    )

    list_filter = (
        "priority",
        "is_active",
        "company",
    )

    search_fields = (
        "candidate__name",
        "candidate__email",
        "candidate__candidate_id",
        "current_company",
        "requisition__requisition_id",
    )

    raw_id_fields = (
        "company",
        "candidate",
        "requisition",
        "recruiter",
    )


# ============================================================
# 5. STAGE HISTORY
# ============================================================

@admin.register(StageHistory)
class StageHistoryAdmin(TrackedAdmin):

    list_display = (
        "candidate",
        "from_stage",
        "to_stage",
        "changed_by",
        "changed_at",
        "company",
    )

    list_filter = (
        "to_stage",
        "from_stage",
        "company",
    )

    search_fields = (
        "candidate__name",
        "candidate__candidate_id",
        "note",
        "changed_by",
    )

    raw_id_fields = (
        "company",
        "candidate",
    )

    readonly_fields = ("changed_at",)
    date_hierarchy = "changed_at"


# ============================================================
# 6. INTERVIEW FEEDBACK INLINE
# ============================================================

class InterviewFeedbackInline(admin.StackedInline):
    model = InterviewFeedback
    extra = 0
    can_delete = False

    raw_id_fields = (
        "company",
        "submitted_by",
    )

    fields = (
        "company",
        "technical_skills",
        "problem_solving",
        "communication",
        "culture_fit",
        "domain_knowledge",
        "leadership",
        "recommendation",
        "strengths",
        "concerns",
        "comments",
        "submitted_by",
        "submitted_by_label",
    )


# ============================================================
# 7. INTERVIEW ROUND
# ============================================================

@admin.register(InterviewRound)
class InterviewRoundAdmin(TrackedAdmin):

    list_display = (
        "interview_id",
        "candidate",
        "round_name",
        "interviewer",
        "scheduled_at",
        "mode",
        "status",
        "feedback_status",
        "company",
        "is_active",
    )

    list_filter = (
        "status",
        "feedback_status",
        "is_active",
        "company",
    )

    search_fields = (
        "interview_id",
        "candidate__name",
        "candidate__candidate_id",
        "round_name",
        "interviewer__name",
        "interviewer__employee_code",
    )

    raw_id_fields = (
        "company",
        "candidate",
        "interviewer",
    )

    date_hierarchy = "scheduled_at"
    inlines = [InterviewFeedbackInline]


# ============================================================
# 8. INTERVIEW FEEDBACK
# ============================================================

@admin.register(InterviewFeedback)
class InterviewFeedbackAdmin(TrackedAdmin):

    list_display = (
        "interview",
        "recommendation",
        "technical_skills",
        "problem_solving",
        "communication",
        "culture_fit",
        "domain_knowledge",
        "leadership",
        "avg_score",
        "submitted_by",
        "is_active",
    )

    list_filter = (
        "recommendation",
        "is_active",
        "company",
    )

    search_fields = (
        "interview__interview_id",
        "interview__candidate__name",
        "submitted_by__name",
    )

    raw_id_fields = (
        "company",
        "interview",
        "submitted_by",
    )

    @admin.display(description="Average Score")
    def avg_score(self, obj):
        return obj.average_score


# ============================================================
# 9. CANDIDATE SELECTION
# ============================================================

@admin.register(CandidateSelection)
class CandidateSelectionAdmin(TrackedAdmin):

    list_display = (
        "candidate",
        "requisition",
        "approved_ctc_lpa",
        "joining_date",
        "reporting_manager",
        "status",
        "decided_by",
        "decided_at",
        "is_active",
    )

    list_filter = (
        "status",
        "is_active",
        "company",
    )

    search_fields = (
        "candidate__name",
        "candidate__candidate_id",
        "requisition__requisition_id",
    )

    raw_id_fields = (
        "company",
        "candidate",
        "requisition",
        "reporting_manager",
    )


# ============================================================
# 10. OFFER
# ============================================================

@admin.register(Offer)
class OfferAdmin(TrackedAdmin):

    list_display = (
        "offer_id",
        "candidate",
        "designation",
        "offered_ctc_lpa",
        "target_joining_date",
        "valid_until",
        "status",
        "sent_at",
        "company",
        "is_active",
    )

    list_filter = (
        "status",
        "is_active",
        "company",
    )

    search_fields = (
        "offer_id",
        "candidate__name",
        "candidate__candidate_id",
        "designation",
    )

    raw_id_fields = (
        "company",
        "candidate",
    )

    date_hierarchy = None


# ============================================================
# 11. DOCUMENT REVIEW
# ============================================================

@admin.register(DocumentReview)
class DocumentReviewAdmin(TrackedAdmin):

    list_display = (
        "document",
        "status",
        "reviewed_by",
        "reviewed_at",
        "is_active",
    )

    list_filter = (
        "status",
        "is_active",
    )

    search_fields = (
        "document__document_name",
        "document__employee__name",
        "document__employee__candidate_id",
        "reviewed_by",
    )

    raw_id_fields = ("document",)


# ============================================================
# 12. BACKGROUND VERIFICATION
# ============================================================

@admin.register(BGVCase)
class BGVCaseAdmin(TrackedAdmin):

    list_display = (
        "candidate",
        "agency",
        "status",
        "result",
        "completed_at",
        "company",
        "is_active",
    )

    list_filter = (
        "status",
        "result",
        "is_active",
        "company",
    )

    search_fields = (
        "candidate__name",
        "candidate__candidate_id",
        "agency",
    )

    raw_id_fields = (
        "company",
        "candidate",
    )
 

# ============================================================
# 13-20. HIRING PLUS AND CANDIDATE PORTAL MODELS
# ============================================================
# Register only if not already registered.
# This avoids AlreadyRegistered errors if other code has
# already registered any of these models.

HIRING_PLUS_MODELS = (
    CandidateApproval,
    HikeApproval,
    IdentityVerification,
    HiringChecklistItem,
    HiringQuestion,
    InterviewerAssignment,
    DocumentUploadLink,
    RequisitionRoles,
    CandidatePortalLink,
    CandidatePortalActivity,
)

for model in HIRING_PLUS_MODELS:
    if not admin.site.is_registered(model):
        admin.site.register(model)


# ============================================================
# 21. CANDIDATE PORTAL ACCOUNT
# ============================================================

@admin.register(CandidatePortalAccount)
class CandidatePortalAccountAdmin(admin.ModelAdmin):

    list_display = (
        "id",
        "email",
        "company",
        "candidate",
        "link",
        "registered_at",
        "last_login_at",
        "failed_attempts",
        "locked_until",
    )

    list_filter = (
        "company",
        "registered_at",
    )

    search_fields = (
        "email",
        "candidate__name",
        "candidate__email",
        "candidate__candidate_id",
    )

    raw_id_fields = (
        "company",
        "candidate",
        "link",
    )

    readonly_fields = (
        "registered_at",
        "last_login_at",
    )

    ordering = ("-id",)
    list_per_page = 25
    save_on_top = True

    def save_model(self, request, obj, form, change):
        # Hash a new or changed plain-text password.
        # Existing Django-encoded hashes are not hashed again.
        if obj.password:
            try:
                identify_hasher(obj.password)
            except (ValueError, TypeError):
                obj.password = make_password(obj.password)

        super().save_model(request, obj, form, change)


# ============================================================
# 22. CANDIDATE PORTAL DRAFT
# ============================================================

@admin.register(CandidatePortalDraft)
class CandidatePortalDraftAdmin(admin.ModelAdmin):

    list_display = (
        "id",
        "company",
        "candidate",
        "step",
        "client_version",
    )

    list_filter = (
        "company",
        "step",
    )

    search_fields = (
        "candidate__name",
        "candidate__email",
        "candidate__candidate_id",
        "step",
    )

    raw_id_fields = (
        "company",
        "candidate",
    )

    ordering = ("step",)
    list_per_page = 25
    save_on_top = True
