# ============================================================
# ADDITIVE: B2B company-wise control tower for the Super Admin
#
# Nothing in the existing code is removed or changed by this file.
#
# WHY THIS FILE EXISTS
# --------------------
# The Recruitment module (company HR panel) stores candidates as
# EmployeeDT rows (Employee_Status="Candidate", 13-stage pipeline in
# EmployeeDT.candidate_status).  The old SuperAdmin candidate screen
# and dashboard only read Employee.Candidate (a separate table), so
# the real company-wise candidates never showed up.
#
# This module reads ALL sources, company by company:
#   1. Recruitment pipeline candidates  (EmployeeDT, same rule as
#      Recruitment.common.candidates_qs)           <- main source
#   2. Candidates added from the SuperAdmin panel   (Employee.Candidate)
#      (copies made by sync_legacy_candidates are skipped so nobody
#       is counted twice)
#   3. Employees (EmployeeDT that are not pending candidates)
#   4. Offers, open requisitions, company admins
# ============================================================

import csv
from collections import OrderedDict, defaultdict

from django.core.paginator import Paginator
from django.db.models import Count, Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, render

from Company.models import company_details
from Employee.models import Candidate, EmployeeDT

from .views import superadmin_required

try:  # CompanyAdmin lives in SuperAdmin.models
    from .models import CompanyAdmin
except Exception:  # pragma: no cover
    CompanyAdmin = None

try:  # Recruitment app is optional for this screen
    from Recruitment.models import JobRequisition, Offer
except Exception:  # pragma: no cover
    JobRequisition = None
    Offer = None


# ------------------------------------------------------------
# STAGE -> BUCKET  (13 recruitment stages shown as 8 columns)
# ------------------------------------------------------------
BUCKETS = OrderedDict(
    [
        ("applied", ("Applied", ["APPLIED", "SCREENING"])),
        ("shortlisted", ("Shortlisted", ["SHORTLISTED"])),
        ("interview", ("Interview", ["INTERVIEW", "FEEDBACK_PENDING"])),
        ("selected", ("Selected", ["SELECTED"])),
        ("offer", ("Offer", ["OFFER_SENT", "OFFER_ACCEPTED"])),
        ("onboarding", ("Onboarding", ["DOCS_PENDING", "BGV", "READY_TO_JOIN"])),
        ("joined", ("Joined", ["JOINED"])),
        ("rejected", ("Rejected", ["REJECTED"])),
    ]
)

STAGE_TO_BUCKET = {}
for _key, (_label, _stages) in BUCKETS.items():
    for _s in _stages:
        STAGE_TO_BUCKET[_s] = _key

STAGE_LABELS = {
    "APPLIED": "Applied",
    "SCREENING": "Screening",
    "SHORTLISTED": "Shortlisted",
    "INTERVIEW": "Interview",
    "FEEDBACK_PENDING": "Feedback Pending",
    "SELECTED": "Selected",
    "OFFER_SENT": "Offer Sent",
    "OFFER_ACCEPTED": "Offer Accepted",
    "DOCS_PENDING": "Docs Pending",
    "BGV": "BGV",
    "READY_TO_JOIN": "Ready To Join",
    "JOINED": "Joined",
    "REJECTED": "Rejected",
}

# Employee.Candidate (SuperAdmin table) uses a shorter status list.
LEGACY_STATUS_MAP = {
    "APPLIED": "APPLIED",
    "SHORTLISTED": "SHORTLISTED",
    "INTERVIEW": "INTERVIEW",
    "SELECTED": "SELECTED",
    "OFFERED": "OFFER_SENT",
    "REJECTED": "REJECTED",
    "HIRED": "JOINED",
}

LEGACY_COPY_MARKER = "Legacy EmployeeDT ID:"  # written by sync_legacy_candidates()


def _bucket(stage):
    code = (stage or "APPLIED").strip().upper() or "APPLIED"
    return STAGE_TO_BUCKET.get(code, "applied")


def company_display_name(company):
    return (
        getattr(company, "Registered_Company_Name", None)
        or getattr(company, "Brand_Name", None)
        or f"Company #{company.pk}"
    )


# ------------------------------------------------------------
# QUERYSETS
# ------------------------------------------------------------
def _candidate_rule():
    """Same rule the company HR panel uses (Recruitment.common.candidates_qs)."""
    return (
        Q(recruitment_profile__isnull=False)
        | Q(Employee_Status="Candidate")
        | (Q(applied_position__isnull=False) & ~Q(applied_position=""))
    )


def _joined_q():
    """Hired people: stage JOINED, or the recruitment flow already activated them."""
    return Q(candidate_status__iexact="JOINED") | Q(Employee_Status="Activate")


def candidates_base_qs():
    """
    ALL recruitment candidates of every company - exactly the rule the company
    HR panel uses (Recruitment.common.candidates_qs).  Includes people who are
    already hired (they are shown as 'Joined').
    """
    return EmployeeDT.objects.filter(_candidate_rule())


def pending_candidates_qs():
    """Candidates still in the hiring pipeline (not hired yet)."""
    return candidates_base_qs().exclude(_joined_q())


def employees_base_qs():
    """Real employees = every EmployeeDT that is not a still-pending candidate."""
    return EmployeeDT.objects.exclude(pk__in=pending_candidates_qs().values("pk"))


def stage_of(obj):
    """Stage code of one EmployeeDT row (Activate = already joined)."""
    if (getattr(obj, "Employee_Status", "") or "") == "Activate":
        return "JOINED"
    return (getattr(obj, "candidate_status", "") or "APPLIED").upper()


def filter_stage(qs, codes):
    """Filter EmployeeDT candidates by stage code(s), JOINED/Activate aware."""
    codes = [c.upper() for c in codes]
    not_active = ~Q(Employee_Status="Activate")
    cond = Q(pk__in=[])
    non_joined = [c for c in codes if c != "JOINED"]
    if non_joined:
        c2 = Q(candidate_status__in=non_joined + [c.lower() for c in non_joined])
        if "APPLIED" in non_joined:
            c2 |= Q(candidate_status__isnull=True) | Q(candidate_status="")
        cond |= c2 & not_active
    if "JOINED" in codes:
        cond |= _joined_q()
    return qs.filter(cond)


def grouped_stage_counts(qs):
    """{company_id: {stage: n}} for an EmployeeDT queryset."""
    out = defaultdict(lambda: defaultdict(int))
    for row in qs.values("company_id", "candidate_status", "Employee_Status").annotate(n=Count("id")):
        if (row["Employee_Status"] or "") == "Activate":
            stage = "JOINED"
        else:
            stage = (row["candidate_status"] or "APPLIED").upper()
        out[row["company_id"]][stage] += row["n"]
    return out


def legacy_candidates_qs():
    """Candidates added from the SuperAdmin panel (skips sync copies)."""
    return Candidate.objects.exclude(notes__icontains=LEGACY_COPY_MARKER)


# ------------------------------------------------------------
# CORE: company-wise numbers (grouped queries, no N+1)
# ------------------------------------------------------------
def build_company_stats(company_qs):
    companies = list(company_qs)
    ids = [c.pk for c in companies]

    # ---- recruitment candidates by stage ----
    stage_counts = grouped_stage_counts(candidates_base_qs().filter(company_id__in=ids))

    # ---- candidates added from SuperAdmin panel ----
    sa_counts = defaultdict(lambda: defaultdict(int))
    for row in (
        legacy_candidates_qs()
        .filter(company_id__in=ids)
        .values("company_id", "candidate_status")
        .annotate(n=Count("id"))
    ):
        mapped = LEGACY_STATUS_MAP.get((row["candidate_status"] or "").upper(), "APPLIED")
        sa_counts[row["company_id"]][mapped] += row["n"]

    # ---- employees ----
    emp = {}
    for row in (
        employees_base_qs()
        .filter(company_id__in=ids)
        .values("company_id")
        .annotate(
            total=Count("id"),
            active=Count("id", filter=Q(is_active=True)),
            with_login=Count("id", filter=Q(account__isnull=False)),
        )
    ):
        emp[row["company_id"]] = row

    # ---- offers ----
    offers = defaultdict(lambda: defaultdict(int))
    if Offer is not None:
        for row in (
            Offer.objects.filter(company_id__in=ids)
            .values("company_id", "status")
            .annotate(n=Count("id"))
        ):
            offers[row["company_id"]][row["status"]] += row["n"]

    # ---- open requisitions ----
    reqs = {}
    if JobRequisition is not None:
        for row in (
            JobRequisition.objects.filter(
                company_id__in=ids, is_active=True, approval_status="Approved"
            )
            .values("company_id")
            .annotate(n=Count("id"))
        ):
            reqs[row["company_id"]] = row["n"]

    # ---- company admins ----
    admins = {}
    if CompanyAdmin is not None:
        for row in (
            CompanyAdmin.objects.filter(company_id__in=ids)
            .values("company_id")
            .annotate(n=Count("id"))
        ):
            admins[row["company_id"]] = row["n"]

    rows = []
    for c in companies:
        buckets = OrderedDict((k, 0) for k in BUCKETS)
        for src in (stage_counts[c.pk], sa_counts[c.pk]):
            for stage, n in src.items():
                buckets[_bucket(stage)] += n

        total_candidates = sum(buckets.values())
        e = emp.get(c.pk, {})
        o = offers[c.pk]
        limit = getattr(c, "employee_limit", 0) or 0
        total_emp = e.get("total", 0)

        rows.append(
            {
                "id": c.pk,
                "name": company_display_name(c),
                "registered_name": getattr(c, "Registered_Company_Name", "") or "",
                "status": getattr(c, "company_status", "") or "",
                "plan": getattr(c, "plan", "") or "",
                "employee_limit": limit,
                "employees_total": total_emp,
                "employees_active": e.get("active", 0),
                "employees_inactive": total_emp - e.get("active", 0),
                "employees_with_login": e.get("with_login", 0),
                "limit_used_pct": min(100, round(total_emp * 100 / limit)) if limit else 0,
                "candidates_total": total_candidates,
                "candidates_in_pipeline": total_candidates
                - buckets["rejected"]
                - buckets["joined"],
                "buckets": buckets,
                "joined": buckets["joined"],
                "stage_counts": dict(stage_counts[c.pk]),
                "superadmin_added_candidates": sum(sa_counts[c.pk].values()),
                "offers_total": sum(o.values()),
                "offers_sent": o.get("Sent", 0),
                "offers_accepted": o.get("Accepted", 0),
                "offers_declined": o.get("Declined", 0),
                "open_requisitions": reqs.get(c.pk, 0),
                "admins": admins.get(c.pk, 0),
            }
        )
    return rows


def build_totals(rows):
    t = {
        "companies": len(rows),
        "employees_total": 0,
        "employees_active": 0,
        "candidates_total": 0,
        "candidates_in_pipeline": 0,
        "joined": 0,
        "offers_total": 0,
        "offers_accepted": 0,
        "open_requisitions": 0,
        "buckets": OrderedDict((k, 0) for k in BUCKETS),
    }
    for r in rows:
        for k in (
            "employees_total",
            "employees_active",
            "candidates_total",
            "candidates_in_pipeline",
            "joined",
            "offers_total",
            "offers_accepted",
            "open_requisitions",
        ):
            t[k] += r[k]
        for k, v in r["buckets"].items():
            t["buckets"][k] += v
    return t


def _filtered_companies(request):
    search = (request.GET.get("search") or "").strip()
    status = (request.GET.get("status") or "").strip().upper()
    qs = company_details.objects.all().order_by("Registered_Company_Name")
    if search:
        qs = qs.filter(
            Q(Registered_Company_Name__icontains=search) | Q(Brand_Name__icontains=search)
        )
    if status:
        qs = qs.filter(company_status=status)
    company = (request.GET.get("company") or "").strip()
    if company.isdigit():
        qs = qs.filter(pk=int(company))
    return qs, search, status


# ------------------------------------------------------------
# 1. OVERVIEW PAGE   /portal/b2b/
# ------------------------------------------------------------
@superadmin_required
def superadmin_b2b_overview(request):
    qs, search, status = _filtered_companies(request)
    rows = build_company_stats(qs)
    return render(
        request,
        "superadmin/b2b_overview.html",
        {
            "rows": rows,
            "totals": build_totals(rows),
            "bucket_labels": [(k, v[0]) for k, v in BUCKETS.items()],
            "search": search,
            "selected_status": status,
            "status_choices": getattr(company_details, "COMPANY_STATUS_CHOICES", []),
        },
    )


# ------------------------------------------------------------
# 2. JSON API   /portal/api/b2b/        (?company=<id>)
# ------------------------------------------------------------
@superadmin_required
def superadmin_b2b_api(request):
    qs, _search, _status = _filtered_companies(request)
    rows = build_company_stats(qs)
    totals = build_totals(rows)
    return JsonResponse({"totals": totals, "companies": rows})


# ------------------------------------------------------------
# 3. CSV EXPORT   /portal/b2b/export/
# ------------------------------------------------------------
@superadmin_required
def superadmin_b2b_export(request):
    qs, _search, _status = _filtered_companies(request)
    rows = build_company_stats(qs)

    response = HttpResponse(content_type="text/csv")
    response["Content-Disposition"] = 'attachment; filename="b2b_company_wise.csv"'
    w = csv.writer(response)
    w.writerow(
        ["Company", "Status", "Plan", "Employee Limit", "Employees", "Active", "Inactive"]
        + [f"Candidates - {v[0]}" for v in BUCKETS.values()]
        + ["Candidates Total", "Offers", "Offers Accepted", "Open Requisitions", "Admins"]
    )
    for r in rows:
        w.writerow(
            [
                r["name"],
                r["status"],
                r["plan"],
                r["employee_limit"],
                r["employees_total"],
                r["employees_active"],
                r["employees_inactive"],
            ]
            + list(r["buckets"].values())
            + [
                r["candidates_total"],
                r["offers_total"],
                r["offers_accepted"],
                r["open_requisitions"],
                r["admins"],
            ]
        )
    return response


# ------------------------------------------------------------
# 4. ONE COMPANY   /portal/b2b/<company_id>/
#    tabs: candidates | employees | offers
# ------------------------------------------------------------
@superadmin_required
def superadmin_b2b_company(request, company_id):
    company = get_object_or_404(company_details, pk=company_id)
    stats = build_company_stats(company_details.objects.filter(pk=company.pk))[0]

    tab = (request.GET.get("tab") or "candidates").strip().lower()
    if tab not in ("candidates", "employees", "offers"):
        tab = "candidates"

    q = (request.GET.get("q") or "").strip()
    bucket = (request.GET.get("stage") or "").strip().lower()
    page_no = request.GET.get("page") or 1

    page = None
    superadmin_candidates = []

    if tab == "candidates":
        qs = candidates_base_qs().filter(company=company).order_by("-created_at", "-id")
        if bucket in BUCKETS:
            qs = filter_stage(qs, BUCKETS[bucket][1])
        if q:
            qs = qs.filter(
                Q(name__icontains=q)
                | Q(email__icontains=q)
                | Q(candidate_id__icontains=q)
                | Q(applied_position__icontains=q)
            )
        page = Paginator(qs, 25).get_page(page_no)
        for c in page.object_list:
            code = stage_of(c)
            c.stage_label = STAGE_LABELS.get(code, code.title())
            c.stage_bucket = _bucket(code)

        superadmin_candidates = list(
            legacy_candidates_qs().filter(company=company).order_by("-created_at")[:100]
        )

    elif tab == "employees":
        qs = (
            employees_base_qs()
            .filter(company=company)
            .select_related("account")
            .order_by("-is_active", "name")
        )
        if q:
            qs = qs.filter(
                Q(name__icontains=q) | Q(email__icontains=q) | Q(employee_code__icontains=q)
            )
        page = Paginator(qs, 25).get_page(page_no)

    else:  # offers
        if Offer is not None:
            qs = (
                Offer.objects.filter(company=company)
                .select_related("candidate")
                .order_by("-created_at")
            )
            if q:
                qs = qs.filter(
                    Q(offer_id__icontains=q)
                    | Q(candidate__name__icontains=q)
                    | Q(designation__icontains=q)
                )
            page = Paginator(qs, 25).get_page(page_no)

    return render(
        request,
        "superadmin/b2b_company.html",
        {
            "company": company,
            "company_name": company_display_name(company),
            "stats": stats,
            "bucket_labels": [(k, v[0]) for k, v in BUCKETS.items()],
            "tab": tab,
            "q": q,
            "selected_stage": bucket,
            "page": page,
            "superadmin_candidates": superadmin_candidates,
        },
    )


# ------------------------------------------------------------
# 5. DEBUG   /portal/b2b/debug/   (raw counts - shows where data lives)
# ------------------------------------------------------------
@superadmin_required
def superadmin_b2b_debug(request):
    from django.db.models import Count as _C

    data = {
        "companies": company_details.objects.count(),
        "employeedt_total": EmployeeDT.objects.count(),
        "employeedt_by_Employee_Status": {
            (r["Employee_Status"] or "(blank)"): r["n"]
            for r in EmployeeDT.objects.values("Employee_Status").annotate(n=_C("id"))
        },
        "employeedt_by_candidate_status": {
            (r["candidate_status"] or "(blank)"): r["n"]
            for r in EmployeeDT.objects.values("candidate_status").annotate(n=_C("id"))
        },
        "employeedt_with_login_account": EmployeeDT.objects.filter(account__isnull=False).count(),
        "employeedt_with_applied_position": EmployeeDT.objects.exclude(applied_position__isnull=True).exclude(applied_position="").count(),
        "candidates_all_rule": candidates_base_qs().count(),
        "candidates_pending": pending_candidates_qs().count(),
        "employees_rule": employees_base_qs().count(),
        "superadmin_Candidate_table": Candidate.objects.count(),
        "per_company": {
            (company_display_name(c)): {
                "employeedt": EmployeeDT.objects.filter(company=c).count(),
                "candidates": candidates_base_qs().filter(company=c).count(),
            }
            for c in company_details.objects.all()[:200]
        },
    }
    try:
        from Recruitment.models import CandidateProfile
        data["Recruitment_CandidateProfile"] = CandidateProfile.objects.count()
    except Exception as exc:  # pragma: no cover
        data["Recruitment_CandidateProfile"] = f"error: {exc}"
    if Offer is not None:
        data["Recruitment_Offer"] = Offer.objects.count()
    return JsonResponse(data, json_dumps_params={"indent": 2})


