# ============================================================
# Projects & Tasks tab + Gantt & Timeline tab (Admin / HR)
#   /api/project-hub/projects/   /api/project-hub/tasks/   /api/project-hub/dependencies/   /api/project-hub/gantt/
# ============================================================
from django.db import transaction
from django.db.models import Count, Q
from django.utils import timezone
from rest_framework.decorators import action
from rest_framework.views import APIView

from Timesheet.views_projects import ProjectViewSet as TsProjectViewSet

from .common import (DONE, HubAuthMixin, HubCrud, ProjectAllocation, ProjectBug, ProjectPlan, ProjectTask, TaskDependency, TimesheetProject,
                     actual_hours_by_task, choice, emp_brief, emp_by_code, err, find_project, find_task, iso, is_overdue, next_wbs, ok, paginate,
                     plan_for, project_hub_row, task_row, task_tree, to_bool, to_date, to_decimal, to_int)
from .engine import has_path, recalc_critical_path


class HubProjectViewSet(TsProjectViewSet):
    """
    The project master is Timesheet.TimesheetProject (single source of truth). This viewset only ADDS the planning
    fields (priority, budget_amount, baseline/approved/forecast dates) through ProjectPlan.

    CRUD   /api/project-hub/projects/                ?status= ?search= ?priority=
    POST   /api/project-hub/projects/                {title, code?, client_department?, manager_employee_code?, status?, priority?, budget_hours?,
                                                      budget_amount?, start_date?, end_date?, description?, is_billable?}
    GET    /api/project-hub/projects/summary/        the 4 cards (Total / Active / Planning & On-Hold / Completed)
    GET    /api/project-hub/projects/<id>/tasks/     WBS tree (milestones -> tasks)
    POST   /api/project-hub/projects/<id>/allocate/  (inherited, same ProjectAllocation table)
    """
    authentication_classes = HubAuthMixin.authentication_classes
    permission_classes = HubAuthMixin.permission_classes
    code = "HUB_PROJECT"
    permission_action_map = {"allocate": "create", "allocations": "view", "entries": "view", "summary": "view", "tasks": "view"}

    def build(self, p):
        return project_hub_row(p, self.request)

    def filter(self, qs, p):
        qs = super().filter(qs, p)
        return qs.filter(plan__priority=p["priority"]) if p.get("priority") else qs

    def apply(self, p, d, creating):
        super().apply(p, d, creating)
        self._plan_in = {k: d[k] for k in ("priority", "budget_amount", "baseline_end_date", "approved_end_date") if k in d}
        if "priority" in d:
            choice(d["priority"], ProjectPlan.PRIORITY, "priority")
        for k in ("budget_amount",):
            if k in d:
                b = to_decimal(d[k])
                if b is not None and b < 0:
                    raise ValueError("budget_amount cannot be negative.")
        for k in ("baseline_end_date", "approved_end_date"):
            if k in d:
                to_date(d[k])

    def after_save(self, p, creating):
        d = getattr(self, "_plan_in", {})
        pl = ProjectPlan.objects.filter(project=p).first()
        if pl is None:
            pl = ProjectPlan(company=p.company, project=p, created_by=self.actor(), baseline_end_date=p.end_date, approved_end_date=p.end_date)
        if "priority" in d:
            pl.priority = d["priority"]
        if "budget_amount" in d:
            pl.budget_amount = to_decimal(d["budget_amount"])
        if "baseline_end_date" in d:
            pl.baseline_end_date = to_date(d["baseline_end_date"])
        if "approved_end_date" in d:
            pl.approved_end_date = to_date(d["approved_end_date"])
        elif not creating and "end_date" in self.request.data and not pl.approved_end_date:
            pl.approved_end_date = p.end_date
        pl.updated_by = self.actor()
        pl.save()
        self._plan_in = {}

    @action(detail=False, methods=["get"], url_path="summary")
    def summary(self, request):
        qs = TimesheetProject.objects.filter(company=self.company(), is_active=True)
        c = {s: qs.filter(status=s).count() for s, _ in TimesheetProject.STATUS}
        return ok("HUB_PROJECT_SUMMARY", "Project summary.", {
            "total_projects": qs.count(), "active_projects": c["Active"], "planning_and_on_hold": c["Planning"] + c["On Hold"],
            "planning": c["Planning"], "on_hold": c["On Hold"], "paused": c["On Hold"], "completed": c["Completed"], "cancelled": c["Cancelled"],
            "labels": {"total_projects": "Enterprise track record", "active_projects": "Currently in execution",
                       "planning_and_on_hold": f"{c['Planning']} planning, {c['On Hold']} paused", "completed": "Delivered to production"}})

    @action(detail=True, methods=["get"], url_path="tasks")
    def tasks(self, request, pk=None):
        p = self.scope().filter(pk=pk, is_active=True).first()
        if p is None:
            return err("NOT_FOUND", "Record not found.", 404)
        return ok("HUB_PROJECT_TASKS", "Task tree.", task_tree(p, request))


# ---------------------------------------------------------------
# tasks / milestones
# ---------------------------------------------------------------
def apply_task(co, t, d, creating, actor_is_self=False):
    if creating:
        t.project = find_project(co, d.get("project"))
    if creating or "title" in d:
        title = (d.get("title") or "").strip()
        if not title:
            raise ValueError("title is required.")
        t.title = title[:250]
    for k in ("description", "blocked_reason"):
        if k in d:
            setattr(t, k, d[k])
    if "is_milestone" in d:
        t.is_milestone = to_bool(d["is_milestone"])
    if "parent" in d or "parent_id" in d:
        ref = d.get("parent", d.get("parent_id"))
        if ref in (None, ""):
            t.parent = None
        else:
            par = find_task(co, ref, t.project)
            if par.pk == t.pk or (t.pk and has_parent_loop(par, t)):
                raise ValueError("A task cannot be its own parent.")
            t.parent = par
    if "assignee_employee_code" in d:
        t.assignee = emp_by_code(co, d["assignee_employee_code"], required=False)
    if "status" in d:
        t.status = choice(d["status"], ProjectTask.STATUS, "status")
        if t.status == "Completed":
            t.progress, t.completed_on = 100, t.completed_on or timezone.localdate()
        elif t.completed_on:
            t.completed_on = None
        if t.status == "Blocked" and not (d.get("blocked_reason") or t.blocked_reason):
            raise ValueError("blocked_reason is required when status is Blocked.")
        if t.status != "Blocked" and "blocked_reason" not in d:
            t.blocked_reason = None
    if "priority" in d:
        t.priority = choice(d["priority"], ProjectTask.PRIORITY, "priority")
    if "progress" in d:
        pr = to_int(d["progress"])
        if pr is None or not 0 <= pr <= 100:
            raise ValueError("progress must be between 0 and 100.")
        t.progress = pr
        if pr == 100 and t.status not in DONE:
            t.status, t.completed_on = "Completed", timezone.localdate()
        elif 0 < pr < 100 and t.status == "To Do":
            t.status = "In Progress"
    for k in ("start_date", "due_date"):
        if k in d:
            setattr(t, k, to_date(d[k]))
    if t.start_date and t.due_date and t.due_date < t.start_date:
        raise ValueError("due_date cannot be before start_date.")
    if "planned_hours" in d:
        h = to_decimal(d["planned_hours"])
        if h is None or h < 0:
            raise ValueError("planned_hours must be 0 or more.")
        t.planned_hours = h
    if "deliverable_verified" in d and not actor_is_self:
        t.deliverable_verified = to_bool(d["deliverable_verified"])
    if creating and not t.wbs_code:
        t.wbs_code = (d.get("wbs_code") or "").strip() or next_wbs(t.project, t.parent)
    elif "wbs_code" in d and d["wbs_code"]:
        t.wbs_code = str(d["wbs_code"]).strip()[:30]


def has_parent_loop(candidate_parent, task):
    n, seen = candidate_parent, set()
    while n is not None and n.pk not in seen:
        if n.pk == task.pk:
            return True
        seen.add(n.pk)
        n = n.parent
    return False


class TaskViewSet(HubCrud):
    """
    CRUD   /api/project-hub/tasks/        ?project=<id|code> ?status= ?assignee=<emp code> ?type=milestone|task ?overdue=true ?search=
    POST   /api/project-hub/tasks/        {project, title, is_milestone?, parent?, assignee_employee_code?, status?, priority?, progress?, start_date?,
                                           due_date?, planned_hours?, description?, deliverable_verified?, predecessors?:[task ids]}
    """
    model = ProjectTask
    code = "HUB_TASK"
    select = ("project", "assignee", "assignee__department")
    search_fields = ("title", "wbs_code", "assignee__name", "project__title")

    def scope(self):
        return super().scope().prefetch_related("predecessor_links")

    def build(self, t):
        return task_row(t, self.request, actual_hours_by_task(t.company, t.project).get(t.id, 0))

    def filter(self, qs, p):
        qs = super().filter(qs, p)
        if p.get("assignee"):
            qs = qs.filter(assignee__employee_code=p["assignee"])
        if p.get("type") in ("milestone", "task"):
            qs = qs.filter(is_milestone=p["type"] == "milestone")
        if to_bool(p.get("overdue")):
            qs = qs.filter(due_date__lt=timezone.localdate()).exclude(status__in=DONE)
        return qs

    def apply(self, t, d, creating):
        apply_task(self.company(), t, d, creating)
        self._preds = d.get("predecessors") if "predecessors" in d else None

    def after_save(self, t, creating):
        if self._preds is not None:
            set_predecessors(self.company(), t, self._preds, self.actor())

    def destroy(self, request, pk=None):
        t = self.scope().filter(pk=pk, is_active=True).first()
        if t is None:
            return err("NOT_FOUND", "Record not found.", 404)
        t.is_active, t.updated_by = False, self.actor()
        t.save()
        TaskDependency.objects.filter(Q(predecessor=t) | Q(successor=t)).update(is_active=False)
        ProjectTask.objects.filter(parent=t).update(parent=t.parent)
        return ok("HUB_TASK_DELETED", "Deleted.", {"id": int(pk)})


def set_predecessors(co, task, ids, actor):
    """Replace the predecessor list of `task` with `ids` (idempotent; rejects cross-project and circular links)."""
    if not isinstance(ids, list):
        raise ValueError("predecessors must be a list of task ids.")
    want = set()
    for i in ids:
        p = find_task(co, i, task.project)
        if p.children.filter(is_active=True).exists():
            raise ValueError("Link the sub-tasks, not the parent phase - a phase takes its dates from its tasks.")
        if p.pk == task.pk or has_path(co, task.pk, p.pk):
            raise ValueError(f"Task {p.wbs_code or p.pk} would create a circular dependency.")
        want.add(p.pk)
    for l in TaskDependency.objects.filter(successor=task):
        if l.predecessor_id in want:
            want.discard(l.predecessor_id)
            if not l.is_active:
                l.is_active = True
                l.save()
        elif l.is_active:
            l.is_active = False
            l.save()
    for pid in want:
        TaskDependency.objects.create(company=co, predecessor_id=pid, successor=task, created_by=actor, updated_by=actor)


class DependencyViewSet(HubCrud):
    """
    GET    /api/project-hub/dependencies/?project=<id|code>
    POST   /api/project-hub/dependencies/   {predecessor, successor, lag_days?}   (same project, no circular link, no duplicate)
    DELETE /api/project-hub/dependencies/<id>/      (also POST .../<id>/delete/)
    """
    model = TaskDependency
    code = "HUB_DEPENDENCY"
    status_field = None
    select = ("predecessor", "successor")

    def build(self, l):
        return {"id": l.id, "predecessor": {"id": l.predecessor_id, "wbs_code": l.predecessor.wbs_code, "title": l.predecessor.title},
                "successor": {"id": l.successor_id, "wbs_code": l.successor.wbs_code, "title": l.successor.title}, "lag_days": l.lag_days}

    def filter(self, qs, p):
        if p.get("project"):
            f = {"predecessor__project_id": int(p["project"])} if str(p["project"]).isdigit() else {"predecessor__project__code__iexact": p["project"]}
            qs = qs.filter(**f)
        return qs

    def apply(self, l, d, creating):
        co = self.company()
        if not creating:
            if "lag_days" in d:
                l.lag_days = to_int(d["lag_days"], 0)
            return
        pred, succ = find_task(co, d.get("predecessor")), find_task(co, d.get("successor"))
        if pred.project_id != succ.project_id:
            raise ValueError("Both tasks must belong to the same project.")
        if pred.children.filter(is_active=True).exists() or succ.children.filter(is_active=True).exists():
            raise ValueError("Link the sub-tasks, not the parent phase - a phase takes its dates from its tasks.")
        if pred.pk == succ.pk or has_path(co, succ.pk, pred.pk):
            raise ValueError("This link would create a circular dependency.")
        if TaskDependency.objects.filter(predecessor=pred, successor=succ, is_active=True).exists():
            raise ValueError("This dependency already exists.")
        stale = TaskDependency.objects.filter(predecessor=pred, successor=succ, is_active=False).first()
        l.predecessor, l.successor, l.lag_days = pred, succ, to_int(d.get("lag_days"), 0)
        if stale:                       # unique_together safety: reuse the soft-deleted row instead of inserting a duplicate
            stale.is_active, stale.lag_days = True, l.lag_days
            stale.save()
            l.pk, l._state.adding = stale.pk, False
            l.created_at = stale.created_at


# ---------------------------------------------------------------
# Gantt & Timeline tab
# ---------------------------------------------------------------
class GanttView(HubAuthMixin, APIView):
    """
    GET  /api/project-hub/gantt/?project=<id|code>&timescale=day|week|month&highlight_critical=true
    POST /api/project-hub/gantt/recalculate/   {project}      [Recalculate Critical Path & Schedule]
    """
    permission_action = "view"

    def get(self, request):
        co = self.company()
        projects = list(TimesheetProject.objects.filter(company=co, is_active=True).values("id", "code", "title", "status"))
        ref = request.query_params.get("project")
        if not ref:
            return ok("HUB_GANTT", "Select a project.", {"projects": projects, "project": None, "cards": gantt_cards(None, None),
                                                          "timescale": request.query_params.get("timescale", "month"), "rows": [], "dependencies": [], "workload": []})
        try:
            p = find_project(co, ref)
        except ValueError as ex:
            return err("VALIDATION", str(ex))
        ts = request.query_params.get("timescale", "month")
        if ts not in ("day", "week", "month"):
            return err("VALIDATION", "timescale must be day, week or month.")
        tasks = list(ProjectTask.objects.filter(project=p, is_active=True).select_related("project", "assignee", "assignee__department")
                     .prefetch_related("predecessor_links").order_by("wbs_code", "id"))
        act = actual_hours_by_task(co, p)
        rows = []
        for t in tasks:
            r = task_row(t, request, act.get(t.id, 0))
            r["bar_start"], r["bar_end"] = iso(t.start_date or t.early_start), iso(t.due_date or t.early_finish)
            r["kind"] = "milestone" if t.is_milestone else ("critical" if t.is_critical else "regular")
            r["depth"] = (t.wbs_code or "").count(".")
            rows.append(r)
        deps = [{"id": l.id, "predecessor": {"id": l.predecessor_id, "wbs_code": l.predecessor.wbs_code, "title": l.predecessor.title},
                 "successor": {"id": l.successor_id, "wbs_code": l.successor.wbs_code, "title": l.successor.title}, "lag_days": l.lag_days}
                for l in TaskDependency.objects.filter(company=co, is_active=True, successor__project=p).select_related("predecessor", "successor")]
        agg = {}
        for t in tasks:
            if t.assignee_id and not t.is_milestone:
                a = agg.setdefault(t.assignee_id, {"employee": emp_brief(t.assignee, request), "tasks": 0, "completed": 0, "in_progress": 0, "logged_hours": 0.0})
                a["tasks"] += 1
                a["completed"] += t.status == "Completed"
                a["in_progress"] += t.status == "In Progress"
        from .common import DailyWorkReport
        from django.db.models import Sum
        for r in DailyWorkReport.objects.filter(company=co, project=p, is_active=True, status="Approved").values("employee_id").annotate(h=Sum("hours")):
            if r["employee_id"] in agg:
                agg[r["employee_id"]]["logged_hours"] = float(r["h"])
        return ok("HUB_GANTT", "Gantt & timeline.", {
            "projects": projects, "project": {"id": p.id, "code": p.code, "title": p.title}, "timescale": ts,
            "highlight_critical_path": request.query_params.get("highlight_critical", "true").lower() != "false",
            "cards": gantt_cards(p, tasks), "rows": rows, "dependencies": deps, "dependency_count": len(deps), "workload": list(agg.values()),
            "workload_assignees": len(agg)})


def gantt_cards(p, tasks):
    if p is None:
        return {"original_baseline_deadline": None, "current_approved_deadline": None, "forecast_projected_finish": None,
                "critical_path_tasks": {"critical": 0, "total": 0, "label": "0 of 0 tasks"}}
    pl = plan_for(p)
    n = [t for t in tasks if t.status != "Cancelled"]
    c = sum(1 for t in n if t.is_critical)
    return {"original_baseline_deadline": iso(pl.baseline_end_date), "current_approved_deadline": iso(pl.approved_end_date or p.end_date),
            "forecast_projected_finish": iso(pl.forecast_end_date), "critical_path_tasks": {"critical": c, "total": len(n), "label": f"{c} of {len(n)} tasks"}}


class GanttRecalculateView(HubAuthMixin, APIView):
    permission_action = "edit"

    def post(self, request):
        try:
            p = find_project(self.company(), request.data.get("project"))
            with transaction.atomic():
                res = recalc_critical_path(p)
        except ValueError as ex:
            return err("VALIDATION", str(ex))
        return ok("HUB_CRITICAL_PATH_RECALCULATED", "Critical path & schedule recalculated.", res)
