# ============================================================
# ADDITIVE: eSSL "Monthly Status Report (Basic Work Duration)" PDF reader
# ------------------------------------------------------------
# Reads the PDF printed by eSSL eTimeTrack / eTime Office ("Monthly Status Report (Basic Work
# Duration)") - one block per employee with 4 rows (Status / InTime / OutTime / Total) and one
# column per day of the month - and returns plain Python data. Nothing is written here; see
# People/essl_sync.py for importing the result.
#
#   Status codes: P present | A absent | 1/2P (½P) half day | WO weekly off | WOP worked on weekly off |
#                 WO½P weekly off + half day
# ============================================================
import re
from collections import defaultdict
from datetime import date

COL0, COLW = 38.0, 25.2          # x of day-1 column start and the width of one day column (points)
ROWS = ("Status", "InTime", "OutTime", "Total")
TIME_RE = re.compile(r"^\d{1,2}:\d{2}$")
STATUS_MAP = {"P": "Present", "A": "Absent", "½P": "Half Day", "1/2P": "Half Day", "WO": "Weekly Off",
              "WOP": "Worked on Weekly Off", "WO½P": "Weekly Off + Half Day", "H": "Holiday", "L": "Leave"}


class PdfFormatError(ValueError):
    pass


def _col(x0):
    d = int((x0 - COL0 + 1.5) // COLW) + 1
    return d if 1 <= d <= 31 else None


def _norm_status(s):
    return s.replace(" ", "").replace("1/2", "½")


def parse_period(text):
    m = re.search(r"([A-Z][a-z]{2})\s+(\d{1,2})\s+(\d{4})\s+To\s+([A-Z][a-z]{2})\s+(\d{1,2})\s+(\d{4})", text)
    if not m:
        return None
    import calendar
    mon = {n: i for i, n in enumerate(calendar.month_abbr) if n}
    return date(int(m.group(3)), mon[m.group(1)], int(m.group(2))), date(int(m.group(6)), mon[m.group(4)], int(m.group(5)))


def parse_report(path_or_file):
    """-> {"period": (start, end) | None, "company": str, "printed_on": str, "employees": [...]}.
    employee = {"code", "name", "department", "days": {day_no: {"status", "status_label", "in", "out", "total"}}}"""
    try:
        import pdfplumber
    except ImportError:                                                       # pragma: no cover
        raise PdfFormatError("The server needs the 'pdfplumber' package to read PDF reports.")
    try:
        pdf = pdfplumber.open(path_or_file)
    except Exception as e:
        raise PdfFormatError(f"Cannot read the PDF: {e}")
    period, company, printed, employees, seen = None, None, None, [], set()
    with pdf:
        for page in pdf.pages:
            words = page.extract_words(x_tolerance=1.5, y_tolerance=2)
            text = " ".join(w["text"] for w in words)
            if "Monthly Status Report" not in text:
                continue
            period = period or parse_period(text)
            m = re.search(r"Company:\s*(.+?)\s+Printed On", text)
            company = company or (m.group(1).strip() if m else None)
            m = re.search(r"Printed On\s*:\s*(.+?\d{2}:\d{2})", text)
            printed = printed or (m.group(1).strip() if m else None)
            dept = None
            for i, w in enumerate(words):
                if w["text"] == "Department:":
                    row = [x["text"] for x in words if abs(x["top"] - w["top"]) < 2 and x["x0"] > w["x1"]]
                    dept = " ".join(row) or None
                    break
            heads = sorted((w for w in words if w["text"] == "Code:" and words[words.index(w) - 1]["text"] == "Emp."),
                           key=lambda w: w["top"])
            for h in heads:
                line = sorted((x for x in words if abs(x["top"] - h["top"]) < 2.5), key=lambda x: x["x0"])
                toks = [x["text"] for x in line]
                try:
                    code = toks[toks.index("Code:") + 1]
                    name = " ".join(toks[toks.index("Name:") + 1:]) if "Name:" in toks else code
                except (ValueError, IndexError):
                    continue
                labels = {}
                for x in words:
                    if x["x0"] < 30 and x["text"] in ROWS and 0 < x["top"] - h["top"] < 90:
                        labels.setdefault(x["text"], x)
                if set(ROWS) - set(labels):
                    continue
                key = (code, page.page_number, round(h["top"]))
                if key in seen:
                    continue
                seen.add(key)
                tops = {r: labels[r]["top"] for r in ROWS}
                cells = {r: defaultdict(list) for r in ROWS}
                for x in words:
                    if x["x0"] < 30 or not (h["top"] < x["top"] < tops["Total"] + 8):
                        continue
                    d = _col(x["x0"])
                    if d is None:
                        continue
                    best = min(ROWS, key=lambda r: abs(x["top"] - tops[r]))
                    # the second line of a wrapped status ("WO½" / "P") sits between Status and InTime
                    if tops["Status"] + 5 < x["top"] < tops["InTime"] - 4:
                        best = "Status"
                    cells[best][d].append((round(x["top"]), x["x0"], x["text"]))
                days = {}
                for d in range(1, 32):
                    st = "".join(t for _, _, t in sorted(cells["Status"].get(d, []))) or None
                    if st is None:
                        continue
                    st = _norm_status(st)
                    tin = "".join(t for _, _, t in sorted(cells["InTime"].get(d, [])))
                    tout = "".join(t for _, _, t in sorted(cells["OutTime"].get(d, [])))
                    tot = "".join(t for _, _, t in sorted(cells["Total"].get(d, [])))
                    days[d] = {"status": st, "status_label": STATUS_MAP.get(st, st),
                               "in": tin if TIME_RE.match(tin) else None, "out": tout if TIME_RE.match(tout) else None,
                               "total": tot or None}
                employees.append({"code": code, "name": name, "department": dept, "days": days})
    if not employees:
        raise PdfFormatError("This does not look like an eSSL 'Monthly Status Report (Basic Work Duration)' PDF.")
    # one employee can continue on another page - merge by code
    merged = {}
    for e in employees:
        t = merged.setdefault(e["code"], {**e, "days": {}})
        t["days"].update(e["days"])
    return {"period": period, "company": company, "printed_on": printed, "employees": list(merged.values())}


def summarize(parsed):
    emps = parsed["employees"]
    worked = [e for e in emps if any(d["in"] for d in e["days"].values())]
    return {"employees_in_report": len(emps), "employees_with_punches": len(worked),
            "day_cells": sum(len(e["days"]) for e in emps),
            "punch_days": sum(1 for e in emps for d in e["days"].values() if d["in"]),
            "complete_days": sum(1 for e in emps for d in e["days"].values() if d["in"] and d["out"]),
            "missing_out_days": sum(1 for e in emps for d in e["days"].values() if d["in"] and not d["out"])}
