"""Care HCM extras 2: in-app dialer, HR assistant, smart insights, daily attendance analysis, notifications, PWA."""
import json
from datetime import datetime, timedelta
from flask import render_template, request, redirect, url_for, flash, abort, jsonify, send_from_directory, make_response, g
import app as A
from app import app, q, ex, S, now, need, HR, MGR, can_see, month_stats, month_bounds, EXTRA_SQL, balances, audit, scope_sql, SUB

EXTRA_SQL += [
    "CREATE TABLE IF NOT EXISTS calls(id INTEGER PRIMARY KEY, employee_id INTEGER, number TEXT, name TEXT, direction TEXT, outcome TEXT, duration INTEGER DEFAULT 0, notes TEXT, created TEXT);",
    "CREATE TABLE IF NOT EXISTS contacts(id INTEGER PRIMARY KEY, employee_id INTEGER, name TEXT, company TEXT, phone TEXT, notes TEXT);"]


# ---------- daily attendance analysis (for charts) ----------
def daily_analysis(m, emps):
    first, last = month_bounds(m)
    keys = {"Present": 0, "Late": 1, "Half Day": 2, "Absent": 3, "Leave": 4}
    agg = [[0] * 5 for _ in range(last.day)]
    for e in emps:
        _, days = month_stats(e, m)
        for i, (_, st, _) in enumerate(days):
            if st in keys:
                agg[i][keys[st]] += 1
    cols = list(zip(*agg)) if agg else [[]] * 5
    return dict(labels=list(range(1, last.day + 1)), present=list(cols[0]), late=list(cols[1]), half=list(cols[2]), absent=list(cols[3]), leave=list(cols[4]))


def more_dash():
    d, td = {}, now().date()
    me, role = g.user["employee_id"], g.user["role"]
    if role in HR:
        emps = q("SELECT e.*, d.name dept FROM employees e LEFT JOIN departments d ON d.id=e.department_id WHERE e.status='Active'")
        m = td.strftime("%Y-%m")
        gross = {}
        tot = 0
        for e in emps:
            v = (e["basic"] or 0) + (e["house"] or 0) + (e["medical"] or 0) + (e["transport"] or 0) + (e["other"] or 0)
            gross[e["dept"] or "Unassigned"] = gross.get(e["dept"] or "Unassigned", 0) + v; tot += v
        d["total_salary"] = tot; d["avg_salary"] = tot / len(emps) if emps else 0
        d["spark"] = json.dumps([q("SELECT count(*) c FROM attendance WHERE day=? AND status IN ('Present','Late','Half Day')", ((td - timedelta(days=i)).isoformat(),), True)["c"] for i in range(6, -1, -1)])
        d["charts2"] = json.dumps(dict(daily=daily_analysis(m, emps), sal=[list(gross.keys()), [round(v) for v in gross.values()]], tot=round(tot)))
        d["insights"] = insights(emps)
        d["board"] = q("SELECT e.full_name, COALESCE(sum(p.claims+p.ar+p.charts+p.calls),0) u, avg(p.quality) ql FROM employees e JOIN productivity p ON p.employee_id=e.id AND p.day>=? WHERE e.status='Active' GROUP BY e.id HAVING u>0 ORDER BY u DESC LIMIT 5", (td.replace(day=1).isoformat(),))
        d["rate_today"] = round(q("SELECT count(*) c FROM attendance WHERE day=? AND status IN ('Present','Late','Half Day')", (td.isoformat(),), True)["c"] * 100 / max(len(emps), 1))
    d["my_units"] = q("SELECT COALESCE(sum(claims+ar+charts+calls),0) u FROM productivity WHERE employee_id=? AND day>=?", (me, td.replace(day=1).isoformat()), True)["u"]
    d["my_target"] = (g.emp["daily_target"] or 0) if g.emp else 0
    return d


# ---------- smart insights (rule-based automation) ----------
def insights(emps):
    out, td = [], now().date()
    first = td.replace(day=1).isoformat()
    for e in emps:
        c, _ = month_stats(e, td.strftime("%Y-%m"))
        if c["late"] >= 3:
            out.append(("warn", "ri-time-line", "Repeated late arrivals", "%s was late %d times this month." % (e["full_name"], c["late"]), url_for("attendance", emp=e["id"])))
        if c["absent"] >= 3:
            out.append(("bad", "ri-user-unfollow-line", "High absence", "%s has %d unexplained absences this month." % (e["full_name"], c["absent"]), url_for("attendance", emp=e["id"])))
    y = (td - timedelta(days=1)).isoformat()
    for r in q("SELECT e.full_name FROM attendance a JOIN employees e ON e.id=a.employee_id WHERE a.day=? AND a.check_out IS NULL", (y,)):
        out.append(("warn", "ri-logout-box-line", "Missed check-out", "%s did not check out yesterday." % r["full_name"], url_for("attendance_day", day=y)))
    for e in emps:
        if (e["daily_target"] or 0) > 0:
            r = q("SELECT count(*) n, COALESCE(sum(claims+ar+charts+calls),0) u FROM productivity WHERE employee_id=? AND day>=?", (e["id"], first), True)
            if r["n"] >= 3 and r["u"] / r["n"] < 0.7 * e["daily_target"]:
                out.append(("warn", "ri-line-chart-line", "Below productivity target", "%s averages %.0f units/day against a target of %.0f." % (e["full_name"], r["u"] / r["n"], e["daily_target"]), url_for("productivity")))
    runs = q("SELECT r.month, COALESCE(sum(s.net),0) t FROM runs r LEFT JOIN slips s ON s.run_id=r.id GROUP BY r.id ORDER BY r.month DESC LIMIT 2")
    if len(runs) == 2 and runs[1]["t"]:
        ch = (runs[0]["t"] - runs[1]["t"]) * 100 / runs[1]["t"]
        if abs(ch) >= 10:
            out.append(("info", "ri-money-dollar-circle-line", "Payroll change", "Net payroll for %s is %+.0f%% versus %s." % (runs[0]["month"], ch, runs[1]["month"]), url_for("payroll")))
    old = q("SELECT count(*) c FROM leaves WHERE status='Pending' AND created<?", ((datetime.now() - timedelta(days=3)).isoformat(),), True)["c"]
    if old:
        out.append(("warn", "ri-calendar-check-line", "Leave requests waiting", "%d leave request(s) have waited more than 3 days." % old, url_for("leave")))
    exp = q("SELECT count(*) c FROM trainings WHERE expires!='' AND expires<?", (td.isoformat(),), True)["c"]
    if exp:
        out.append(("bad", "ri-shield-keyhole-line", "Expired training", "%d training/certification record(s) have expired." % exp, url_for("module", key="trainings")))
    if not out:
        out.append(("ok", "ri-checkbox-circle-line", "All clear", "No issues detected right now. Insights update automatically from attendance, payroll, training and leave data.", url_for("reports")))
    return out[:8]


# ---------- HR assistant (rule-based, answers from your own data) ----------
@app.route("/assistant", methods=["POST"])
@need()
def assistant():
    t = ((request.get_json(silent=True) or {}).get("q") or "").lower()
    howto = any(x in t for x in ("how do", "how to", "how can", "how is", "how are", "how should", "where do", "where can", "what is", "explain", "steps"))
    me, role = g.user["employee_id"], g.user["role"]
    td = now().date()
    if not howto and any(w in t for w in ("leave balance", "how many leave", "leaves left", "my leave balance")):
        return jsonify(a="Your leave balance: " + "; ".join("%s %.1f of %d" % (b["name"], b["left"], b["total"]) for b in balances(me) if b["total"] < 365) + ".")
    if "holiday" in t:
        h = q("SELECT * FROM holidays WHERE day>=? ORDER BY day LIMIT 3", (td.isoformat(),))
        return jsonify(a=("Upcoming holidays: " + ", ".join("%s (%s)" % (x["name"], x["day"]) for x in h) + ".") if h else "No upcoming holidays have been added yet.")
    if not howto and any(w in t for w in ("my payslip", "latest payslip", "last payslip", "my salary slip", "my net pay", "my net salary")):
        s = q("SELECT s.net, r.month, s.id FROM slips s JOIN runs r ON r.id=s.run_id WHERE s.employee_id=? AND r.status='Final' ORDER BY r.month DESC LIMIT 1", (me,), True)
        return jsonify(a=("Your latest payslip is for %s: net pay %s %s." % (s["month"], S("currency"), format(s["net"], ",.0f"))) if s else "No finalized payslip is available for you yet.", link=url_for("payslip", sid=s["id"]) if s else None)
    if any(w in t for w in ("checked in today", "did i check in", "attendance today", "my attendance today")):
        r = q("SELECT * FROM attendance WHERE employee_id=? AND day=?", (me, td.isoformat()), True)
        return jsonify(a=("Today you checked in at %s%s." % (r["check_in"], (" and out at " + r["check_out"]) if r["check_out"] else "")) if r else "You have not checked in today yet.")
    if any(w in t for w in ("who is on leave", "who's on leave", "away", "on leave")):
        n = [r["full_name"] for r in q("SELECT DISTINCT e.full_name FROM leaves l JOIN employees e ON e.id=l.employee_id WHERE l.status='Approved' AND l.start<=? AND l.end>=?", (td.isoformat(),) * 2)]
        return jsonify(a=("On leave today: " + ", ".join(n) + ".") if n else "Nobody is on approved leave today.")
    if "goal" in t or "kpi" in t:
        g_ = q("SELECT title, progress FROM goals WHERE employee_id=? AND status!='Completed' LIMIT 4", (me,))
        return jsonify(a=("Your open goals: " + "; ".join("%s (%d%%)" % (x["title"], x["progress"] or 0) for x in g_) + ".") if g_ else "You have no open goals.")
    if any(w in t for w in ("pending", "approve", "approval")) and role in MGR:
        p = q("SELECT count(*) c FROM leaves WHERE status='Pending'", one=True)["c"]
        return jsonify(a="There are %d pending leave request(s). Open Leave to review them." % p, link=url_for("leave"))
    if any(w in t for w in ("headcount", "how many employees", "total employees")) and role in HR:
        return jsonify(a="There are %d active employees." % q("SELECT count(*) c FROM employees WHERE status='Active'", one=True)["c"])
    if "policy" in t or "policies" in t:
        return jsonify(a="Open Policies to read and acknowledge company policies.", link=url_for("policies"))
    if "expense" in t or "reimburse" in t:
        return jsonify(a="Submit an expense claim under Pay > Expenses. Approved claims are reimbursed in the next payroll.", link=url_for("module", key="expenses"))
    import helpbot
    text, link = helpbot.answer(t)
    if link:
        link = url_for("module", key=link[2:]) if link.startswith("m:") else url_for(link)
    return jsonify(a=text, link=link)


# ---------- dialer ----------
@app.route("/dialer")
@need()
def dialer():
    me, role = g.user["employee_id"], g.user["role"]
    td = now().date().isoformat()
    mine = q("SELECT * FROM calls WHERE employee_id=? ORDER BY id DESC LIMIT 25", (me,))
    stats = q("SELECT count(*) n, COALESCE(sum(duration),0) s, COALESCE(sum(CASE WHEN outcome='Connected' THEN 1 ELSE 0 END),0) ok FROM calls WHERE employee_id=? AND substr(created,1,10)=?", (me, td), True)
    sc, sa = scope_sql("e.id")
    team = q("SELECT e.full_name, count(c.id) n, COALESCE(sum(c.duration),0) s FROM employees e LEFT JOIN calls c ON c.employee_id=e.id AND substr(c.created,1,10)=? WHERE e.status='Active'" + sc + " GROUP BY e.id HAVING n>0 ORDER BY n DESC", [td] + sa) if (role in MGR or g.has_team) else []
    return render_template("dialer.html", mine=mine, stats=stats, team=team,
                           contacts=q("SELECT * FROM contacts WHERE employee_id=? ORDER BY name", (me,)), dirs=q("SELECT full_name, phone, designation FROM employees WHERE status='Active' AND phone IS NOT NULL AND phone!='' ORDER BY full_name"))


@app.route("/dialer/log", methods=["POST"])
@need()
def dialer_log():
    me = g.user["employee_id"]
    f = request.form
    ex("INSERT INTO calls(employee_id,number,name,direction,outcome,duration,notes,created) VALUES(?,?,?,?,?,?,?,?)",
       (me, f.get("number", "")[:30], f.get("name", "")[:60], f.get("direction", "Outbound"), f.get("outcome", "Connected"), int(f.get("duration") or 0), f.get("notes", "")[:300], now().strftime("%Y-%m-%d %H:%M")))
    ex("INSERT INTO productivity(employee_id,day,calls) VALUES(?,?,1) ON CONFLICT(employee_id,day) DO UPDATE SET calls=calls+1", (me, now().date().isoformat()))
    flash("Call logged. It was added to today's productivity.", "ok")
    return redirect(url_for("dialer"))


@app.route("/dialer/contact", methods=["POST"])
@need()
def dialer_contact():
    f = request.form
    if f.get("del"):
        ex("DELETE FROM contacts WHERE id=? AND employee_id=?", (f["del"], g.user["employee_id"]))
    elif f.get("name") and f.get("phone"):
        ex("INSERT INTO contacts(employee_id,name,company,phone,notes) VALUES(?,?,?,?,?)", (g.user["employee_id"], f["name"][:60], f.get("company", "")[:60], f["phone"][:30], f.get("notes", "")[:200]))
    return redirect(url_for("dialer"))


# ---------- notifications for the top bar ----------
@app.context_processor
def _topbar():
    if not g.get("user"):
        return {}
    n, role, me = 0, g.user["role"], g.user["employee_id"]
    try:
        if role in HR:
            n = sum(q("SELECT count(*) c FROM %s WHERE status='%s'" % (t, s), one=True)["c"] for t, s in (("leaves", "Pending"), ("expenses", "Pending"), ("loans", "Pending"), ("regularizations", "Pending")))
        elif g.has_team:
            n = q("SELECT count(*) c FROM leaves l WHERE l.status='Pending' AND l.employee_id IN " + SUB, (me,), True)["c"]
    except Exception:
        n = 0
    return dict(notif=n)


# ---------- PWA ----------
@app.route("/manifest.webmanifest")
def manifest():
    r = make_response(json.dumps({"name": "Care HCM", "short_name": "Care HCM", "start_url": "/", "display": "standalone", "background_color": "#F4F3FB", "theme_color": "#231F52",
                                  "icons": [{"src": "/static/img/icon-192.png", "sizes": "192x192", "type": "image/png"}, {"src": "/static/img/icon-512.png", "sizes": "512x512", "type": "image/png"}]}))
    r.headers["Content-Type"] = "application/manifest+json"
    return r


@app.route("/sw.js")
def sw():
    r = make_response("self.addEventListener('install',e=>self.skipWaiting());self.addEventListener('activate',e=>e.waitUntil(self.clients.claim()));self.addEventListener('fetch',e=>{});")
    r.headers["Content-Type"] = "application/javascript"
    r.headers["Cache-Control"] = "no-cache"
    return r
