# ============================================================
# Critical-path solver + analytics (pure computation, no duplicate storage)
# ============================================================
import math
from collections import defaultdict
from datetime import timedelta
from decimal import Decimal

from django.utils import timezone

from .common import (DONE, DailyWorkReport, ProjectPlan, ProjectTask, TaskDependency, actual_hours_by_task, emp_brief, is_overdue,
                     plan_for)


def _duration(t):
    if t.start_date and t.due_date and t.due_date >= t.start_date:
        return (t.due_date - t.start_date).days + 1
    if t.planned_hours and t.planned_hours > 0:
        return max(1, int(math.ceil(float(t.planned_hours) / 8)))
    return 1


def has_path(company, src_id, dst_id):
    """True if dst is reachable from src through finish-to-start links (used to block circular dependencies)."""
    graph = defaultdict(list)
    for l in TaskDependency.objects.filter(company=company, is_active=True).values("predecessor_id", "successor_id"):
        graph[l["predecessor_id"]].append(l["successor_id"])
    seen, stack = set(), [src_id]
    while stack:
        n = stack.pop()
        if n == dst_id:
            return True
        if n in seen:
            continue
        seen.add(n)
        stack.extend(graph.get(n, []))
    return False


def recalc_critical_path(project):
    """Forward/backward pass. Writes early_start/early_finish/slack_days/is_critical on tasks and
    forecast_end_date on the plan. Returns a small summary. Raises ValueError on a dependency cycle."""
    all_tasks = list(ProjectTask.objects.filter(project=project, is_active=True).exclude(status="Cancelled"))
    parents = {t.parent_id for t in all_tasks if t.parent_id}
    tasks = [t for t in all_tasks if t.id not in parents]          # leaf tasks/milestones form the network; parents are roll-ups
    plan = plan_for(project)
    if not tasks:
        plan.forecast_end_date = None
        plan.save(update_fields=["forecast_end_date"])
        return {"tasks": 0, "critical": 0, "forecast_finish": None}
    ids = {t.id for t in tasks}
    links = [(l.predecessor_id, l.successor_id, l.lag_days) for l in
             TaskDependency.objects.filter(company=project.company, is_active=True, predecessor_id__in=ids, successor_id__in=ids)]
    preds, succs = defaultdict(list), defaultdict(list)
    for p, s, lag in links:
        preds[s].append((p, lag))
        succs[p].append((s, lag))
    # topological order
    indeg = {t.id: len(preds[t.id]) for t in tasks}
    order, queue = [], [i for i, d in indeg.items() if d == 0]
    while queue:
        n = queue.pop(0)
        order.append(n)
        for s, _ in succs[n]:
            indeg[s] -= 1
            if indeg[s] == 0:
                queue.append(s)
    if len(order) != len(tasks):
        raise ValueError("Circular task dependency found - remove the loop and try again.")
    by_id = {t.id: t for t in tasks}
    anchor = project.start_date or min([t.start_date for t in tasks if t.start_date] or [timezone.localdate()])
    ES, EF, dur = {}, {}, {i: _duration(by_id[i]) for i in by_id}
    for i in order:
        t = by_id[i]
        start = max(anchor, t.start_date) if t.start_date else anchor
        for p, lag in preds[i]:
            start = max(start, EF[p] + timedelta(days=1 + lag))
        ES[i], EF[i] = start, start + timedelta(days=dur[i] - 1)
    finish = max(EF.values())
    LF, LS = {}, {}
    for i in reversed(order):
        lf = finish
        for s, lag in succs[i]:
            lf = min(lf, LS[s] - timedelta(days=1 + lag))
        LF[i], LS[i] = lf, lf - timedelta(days=dur[i] - 1)
    out, crit = [], 0
    for i, t in by_id.items():
        slack = (LS[i] - ES[i]).days
        t.early_start, t.early_finish, t.slack_days, t.is_critical = ES[i], EF[i], slack, slack <= 0 and t.status != "Completed"
        crit += 1 if t.is_critical else 0
        out.append(t)
    kids = defaultdict(list)
    by_all = {t.id: t for t in all_tasks}
    for t in all_tasks:
        if t.parent_id in by_all:
            kids[t.parent_id].append(t)

    def roll(t):                                     # parent = earliest child start .. latest child finish; critical if any child is
        ch = kids.get(t.id)
        if not ch:
            return t
        done = [roll(c) for c in ch if c.early_start]
        if done:
            t.early_start, t.early_finish = min(c.early_start for c in done), max(c.early_finish for c in done)
            t.slack_days, t.is_critical = min(c.slack_days for c in done), any(c.is_critical for c in done)
            out.append(t)
        return t
    for t in all_tasks:
        if t.parent_id not in by_all:
            roll(t)
    ProjectTask.objects.bulk_update({t.id: t for t in out}.values(), ["early_start", "early_finish", "slack_days", "is_critical"])
    plan.forecast_end_date = finish
    plan.save(update_fields=["forecast_end_date"])
    return {"tasks": len(tasks), "critical": crit, "forecast_finish": finish.isoformat()}


# ---------------------------------------------------------------
# analytics
# ---------------------------------------------------------------
def _workdays(a, b):
    n, d = 0, a
    while d <= b:
        n += d.weekday() < 5
        d += timedelta(days=1)
    return n


def score_for(company, emp_tasks, emp, project=None, window_days=30):
    """Composite = 50% on-time completion + 30% approved daily-report consistency + 20% verified deliverables.
    Returns dict (score None when the employee has no scorable data)."""
    today = timezone.localdate()
    due = [t for t in emp_tasks if t.status == "Completed" or is_overdue(t, today)]
    on_time = [t for t in due if t.status == "Completed" and (t.due_date is None or (t.completed_on or today) <= t.due_date)]
    done = [t for t in emp_tasks if t.status == "Completed"]
    verified = [t for t in done if t.deliverable_verified]
    a, b = today - timedelta(days=window_days - 1), today
    wd = _workdays(a, b)
    rq = DailyWorkReport.objects.filter(company=company, employee=emp, is_active=True, status="Approved", report_date__gte=a, report_date__lte=b)
    if project is not None:
        rq = rq.filter(project=project)
    days_reported = rq.values("report_date").distinct().count()
    r_on_time = (len(on_time) / len(due) * 100) if due else None
    r_consist = min(100.0, days_reported / wd * 100) if (wd and emp_tasks) else None
    r_verified = (len(verified) / len(done) * 100) if done else None
    if r_on_time is None and r_verified is None:       # nothing due / delivered yet -> no honest score
        score = None
    else:
        score = round(0.5 * (r_on_time or 0) + 0.3 * (r_consist or 0) + 0.2 * (r_verified or 0), 1)
    return {"score": score, "on_time_completion_rate": None if r_on_time is None else round(r_on_time, 1),
            "report_consistency_rate": None if r_consist is None else round(r_consist, 1),
            "verified_deliverables_rate": None if r_verified is None else round(r_verified, 1),
            "tasks_assigned": len(emp_tasks), "tasks_completed": len(done), "reports_approved_last_30_days": days_reported}


def analytics(company, project=None, request=None):
    today = timezone.localdate()
    tq = ProjectTask.objects.filter(company=company, is_active=True, project__is_active=True).exclude(status="Cancelled").select_related("assignee", "assignee__department")
    if project is not None:
        tq = tq.filter(project=project)
    tasks = list(tq)
    ms = [t for t in tasks if t.is_milestone]
    work = [t for t in tasks if not t.is_milestone]
    ms_done = sum(1 for t in ms if t.status == "Completed")
    resolved = [t for t in work if t.status == "Completed"]
    on_time = [t for t in resolved if t.due_date is None or (t.completed_on or today) <= t.due_date]
    planned = sum((t.planned_hours for t in work), Decimal("0"))
    act = actual_hours_by_task(company, project)
    rq = DailyWorkReport.objects.filter(company=company, is_active=True, status="Approved")
    if project is not None:
        rq = rq.filter(project=project)
    from django.db.models import Sum
    actual = rq.aggregate(h=Sum("hours"))["h"] or Decimal("0")
    blocked = sum(1 for t in tasks if t.status == "Blocked")
    past = sum(1 for t in tasks if is_overdue(t, today))
    by_emp = defaultdict(list)
    for t in work:
        if t.assignee_id:
            by_emp[t.assignee].append(t)
    workload, contrib = [], []
    for emp, ts in by_emp.items():
        hrs = rq.filter(employee=emp).aggregate(h=Sum("hours"))["h"] or Decimal("0")
        workload.append({"employee": emp_brief(emp, request), "tasks": len(ts), "completed": sum(1 for t in ts if t.status == "Completed"),
                         "in_progress": sum(1 for t in ts if t.status == "In Progress"), "overdue": sum(1 for t in ts if is_overdue(t, today)),
                         "blocked": sum(1 for t in ts if t.status == "Blocked"), "logged_hours": float(hrs)})
        contrib.append({"employee": emp_brief(emp, request), **score_for(company, ts, emp, project)})
    contrib.sort(key=lambda r: (r["score"] is None, -(r["score"] or 0)))
    pct = lambda a, b: round(a * 100 / b) if b else 0
    return {
        "cards": {"milestone_completion": {"percent": pct(ms_done, len(ms)), "label": f"{ms_done} of {len(ms)} phases completed"},
                  "on_time_task_delivery": {"percent": pct(len(on_time), len(resolved)), "label": f"{len(on_time)} of {len(resolved)} tasks resolved"},
                  "planned_vs_actual_hours": {"planned": float(planned), "actual": float(actual), "variance": float(actual - planned),
                                              "label": "Zero budget variance" if actual == planned else f"{float(actual - planned):+g}h variance"},
                  "overdue_and_blocked": {"total": blocked + past, "blocked": blocked, "past_deadline": past,
                                          "label": f"{blocked} blocked, {past} past deadline"}},
        "employee_workload": {"active_contributors": len(workload), "rows": workload},
        "employee_contributions": {"formula": "Composite Score = (50% x Task On-Time Completion Rate) + (30% x Approved Daily Report Consistency) + (20% x Verified Deliverables Rate)",
                                   "note": "Performance is never measured by raw hours logged alone.", "rows": contrib}}
