"""QA TC4 / AC#7 - audits team-attendance employee IDs against erp-api's own
org chart, live.

The gap this closes
-------------------
The unit tests in test_team_attendance_summary.py (TestAC7HierarchyScope) pin
this service's half: it renders erp-api's rows and never widens them. They
cannot check the half that actually matters to TC4 - whether the rows erp-api
returned are inside the manager's hierarchy - because that lives in erp-api's
org chart, which no test fixture has.

This script does that check against the live system, so "no leakage from
lateral teams" is verified rather than assumed.

How the permitted set is obtained
---------------------------------
erp-api has no "list my org chart" route, but it already states the caller's
permitted employee set on GET /api/v1/ai/leave/pending/teams: a name search
matching nobody comes back search_matched=false with the manager's WHOLE team
roster attached (erp-api's "pick from your team"). Querying it with a
deliberately unmatchable name enumerates that set. It is erp-api's own answer
about who this manager may see - not a list this script assembles.

What is checked
---------------
Two checks, because the sharper one cannot run every day:

  POPULATION (every date) - erp-api's own `total_team` count against the size
    of the permitted set. A summary built over MORE people than the manager
    may see is a scope defect visible without a single exception row. This
    exists because the identity check below only has data on dates that have
    missing punches, and most dates do not: on its own it spent nearly every
    run examining nothing, and a check that reports INCONCLUSIVE most days is
    one that gets ignored or switched off. A total_team SMALLER than the
    permitted set is not a finding - a narrower summary leaks nothing.

  IDENTITY (dates with missing-punch rows) - each returned employee ID
    against the permitted set. Sharper when it runs, because it names the
    employee rather than a count.

Reading the result
------------------
ANY returned employee outside the permitted set FAILS. A possible leak is not
something to wave through, so the verdict never depends on how confident the
diagnosis is - only the explanation does:

  * the roster covers all `total_team` members
    -> conclusive. There is no unlisted indirect report the row could be,
       whether or not the two endpoints label their scope the same way.
  * the roster is smaller than `total_team`
    -> still FAIL, but flagged as needing confirmation: the permitted set
       enumerated here may be incomplete, and a legitimate indirect report
       (which AC#7 allows) would look identical to a leak. The IDs are
       printed so a reviewer can settle it against the org chart, and
       --lenient-on-scope-mismatch downgrades ONLY this case, only when the
       two endpoints also report different scopes, and only when the
       population check itself passed - a population overflow is never
       explained by an unlisted indirect report, since it says the summary
       counted more people than the manager may see whatever their relation.

Exit codes, so a pipeline can gate on this:
    0  PASS          every check that ran found nothing outside the
                     permitted set. A quiet day with no missing punches
                     still passes on the population check.
    1  FAIL          at least one check found something outside it
    2  INCONCLUSIVE  NEITHER check could run - the roster was not
                     enumerable, or erp-api returned no total_team and no
                     employee rows. Deliberately NOT 0: an audit that
                     audited nothing is not a passing audit.

Run:
    LIVE_TEST_USER_EMAIL=... LIVE_TEST_USER_PASSWORD=... \
    LIVE_ERP_API_URL=https://erp-api14.studyineurope.xyz \
    python tests/verify_attendance_hierarchy_scope.py [--date 2026-08-12]
"""
import argparse
import asyncio
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import httpx

import services.erp_client as erp_client

ERP_API_URL = os.getenv("LIVE_ERP_API_URL") or os.getenv("ERP_API_URL", "")

# Chosen to match no real employee name, so erp-api answers with the roster
# rather than a shortlist. Not a magic value - any unmatchable string works.
_UNMATCHABLE_NAME = "zzzz-no-such-employee-zzzz"

EXIT_PASS = 0
EXIT_FAIL = 1
EXIT_INCONCLUSIVE = 2


async def _login(email: str, password: str) -> str:
    async with httpx.AsyncClient(timeout=20.0) as client:
        resp = await client.post(
            f"{ERP_API_URL}/api/v1/login",
            json={"email": email, "password": password,
                  "browser_id": "verify-attendance-hierarchy-scope"},
        )
    resp.raise_for_status()
    body = resp.json()
    if not body.get("success"):
        raise RuntimeError(f"erp-api login failed: {body.get('message')}")
    return body["data"]["token"]


def _employee_id(row: dict):
    for key in ("employee_id", "id", "user_id"):
        if row.get(key) is not None:
            return row[key]
    return None


def _label(row: dict) -> str:
    name = row.get("employee_name") or row.get("name") or "?"
    number = row.get("employee_number") or row.get("emp_no")
    return f"{name} ({number})" if number else name


async def audit(token: str, date: str | None, lenient_on_scope_mismatch: bool = False) -> int:
    summary = await erp_client.get_team_attendance_summary(token, date=date)
    data = (summary.get("body") or {}).get("data") or {}
    attendance_scope = data.get("scope")
    total_team = ((data.get("summary_cards") or {}).get("total_team") or {}).get("value")
    rows = ((data.get("missing_punch_details") or {}).get("employees")) or []

    roster_result = await erp_client.get_team_pending_leaves(
        token, employee_name=_UNMATCHABLE_NAME)
    roster_data = (roster_result.get("body") or {}).get("data") or {}
    roster = roster_data.get("employees") or []
    roster_scope = roster_data.get("access_scope") or roster_data.get("scope")

    print(f"attendance date        : {data.get('date')}")
    print(f"attendance scope       : {attendance_scope!r}  "
          f"({len(rows)} employee row(s), total_team={total_team})")
    print(f"org-chart scope        : {roster_scope!r}  ({len(roster)} employee(s) permitted)")
    print()

    if roster_data.get("search_matched") is not False or not roster:
        print("INCONCLUSIVE - erp-api did not return the roster for an unmatchable "
              "name, so the permitted set could not be enumerated. Nothing was "
              "audited; this is NOT a pass.")
        return EXIT_INCONCLUSIVE

    permitted = {_employee_id(e) for e in roster if _employee_id(e) is not None}
    for e in sorted(roster, key=lambda r: str(_label(r))):
        print(f"  permitted: {_employee_id(e)} {_label(e)}")
    print()

    checks_run = []
    findings = []

    # ── Check 1: POPULATION ─────────────────────────────────────────────────
    # Runs on every date, which is the point of it. The identity check below
    # can only look at missing-punch rows, and most days have none - so on its
    # own this audit spent most of its runs examining nothing and reporting
    # INCONCLUSIVE, which in a pipeline is a check that is red or ignored
    # rather than one that tests anything.
    #
    # total_team is erp-api's own count of the team it just summarised. If it
    # exceeds the set the manager is permitted to see, the summary is built
    # over more people than the hierarchy allows - a scope defect visible
    # without a single exception row. A SMALLER count is not a finding:
    # a narrower summary leaks nothing.
    if total_team is None:
        print("population : erp-api returned no total_team value - not checked.")
    else:
        checks_run.append("population")
        if total_team > len(permitted):
            findings.append(
                f"attendance summarised total_team={total_team} but the manager is "
                f"permitted to see only {len(permitted)} employee(s)"
            )
            print(f"population : OUTSIDE - total_team={total_team} exceeds the "
                  f"{len(permitted)} permitted employee(s).")
        elif total_team < len(permitted):
            print(f"population : ok - total_team={total_team} is narrower than the "
                  f"{len(permitted)} permitted employee(s); a narrower summary "
                  f"leaks nothing.")
        else:
            print(f"population : ok - total_team={total_team} matches the permitted "
                  f"set exactly.")

    # ── Check 2: IDENTITY ───────────────────────────────────────────────────
    # Sharper than the population check when it can run: it names the actual
    # employee. It just cannot run on a date with no missing-punch rows, which
    # is why it is no longer the only check.
    outside = [r for r in rows if _employee_id(r) not in permitted]
    if not rows:
        print("identity   : not checked - no missing-punch employee rows on this "
              "date. Use --date on a day with exceptions to exercise it.")
    else:
        checks_run.append("identity")
        for r in rows:
            mark = "OUTSIDE" if _employee_id(r) not in permitted else "ok     "
            print(f"  {mark}  : {_employee_id(r)} {_label(r)}")
        if outside:
            findings.append(
                f"{len(outside)} returned employee(s) outside the permitted set: "
                + ", ".join(f"{_employee_id(r)} {_label(r)}" for r in outside)
            )
        else:
            print(f"identity   : ok - all {len(rows)} returned employee(s) are "
                  f"inside the permitted set.")
    print()

    if not checks_run:
        print("INCONCLUSIVE - neither check could run: erp-api returned no "
              "total_team and no employee rows. Nothing was audited; this is NOT "
              "a pass.")
        return EXIT_INCONCLUSIVE

    if not findings:
        print(f"PASS - {' and '.join(checks_run)} check(s) found nothing outside "
              f"the manager's permitted set.")
        return EXIT_PASS

    for finding in findings:
        print(f"FAIL - {finding}")

    # Whether the roster is the WHOLE team, or only part of it. When erp-api's
    # own total_team matches the roster size, the two endpoints are describing
    # the same population, so an ID outside it cannot be an unlisted indirect
    # report - the finding is conclusive on its own terms. When they disagree,
    # the roster is a subset and an indirect report would look identical to a
    # leak; the finding still FAILS (a possible leak is not something to pass
    # silently), but the reviewer is told which of the two it might be.
    roster_covers_team = total_team is not None and len(roster) == total_team
    scopes_agree = attendance_scope == roster_scope

    if roster_covers_team and scopes_agree:
        print(f"Conclusive: both endpoints report scope {attendance_scope!r} and the "
              f"roster covers all {total_team} team member(s), so this is a real "
              f"leak from outside the reporting hierarchy.")
    elif roster_covers_team:
        print(f"Conclusive on population: the scopes are labelled differently "
              f"({attendance_scope!r} vs {roster_scope!r}), but the roster already "
              f"covers all {total_team} team member(s), so there is no unlisted "
              f"indirect report this could be.")
    else:
        print(f"Needs confirmation against the org chart: the roster lists "
              f"{len(roster)} employee(s) but erp-api reports total_team="
              f"{total_team}, so the permitted set enumerated here may be "
              f"incomplete and an indirect report would look the same as a leak. "
              f"Failing rather than passing - a possible leak is not something to "
              f"wave through. Re-run with --lenient-on-scope-mismatch once each ID "
              f"above has been confirmed legitimate.")
        # Scoped to the IDENTITY finding only. A population overflow is not
        # explained by an unlisted indirect report - it says the summary
        # counted MORE people than the manager may see, whatever their
        # relation - so it is never downgraded.
        if (lenient_on_scope_mismatch and not scopes_agree
                and outside and len(findings) == 1):
            print("--lenient-on-scope-mismatch set and the two scopes differ - "
                  "downgrading to REVIEW (exit 0).")
            return EXIT_PASS

    return EXIT_FAIL


async def _main_async(date: str | None, lenient: bool) -> int:
    email = os.getenv("LIVE_TEST_USER_EMAIL")
    password = os.getenv("LIVE_TEST_USER_PASSWORD")
    if not email or not password:
        raise RuntimeError("LIVE_TEST_USER_EMAIL and LIVE_TEST_USER_PASSWORD must be set.")
    if not ERP_API_URL:
        raise RuntimeError("LIVE_ERP_API_URL (or ERP_API_URL) must be set.")

    erp_client.ERP_API_URL = ERP_API_URL
    print(f"erp-api: {ERP_API_URL}")
    print(f"logging in as {email}...\n")
    token = await _login(email, password)
    return await audit(token, date, lenient_on_scope_mismatch=lenient)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--date", help="YYYY-MM-DD; omitted, erp-api uses today")
    parser.add_argument(
        "--lenient-on-scope-mismatch", action="store_true",
        help="Downgrade a FAIL to REVIEW (exit 0) ONLY when the roster could not "
             "cover the whole team AND the two endpoints report different scopes - "
             "i.e. when an unlisted indirect report is a real explanation. Use it "
             "after confirming the named IDs against the org chart, never to make "
             "a red pipeline green.",
    )
    args = parser.parse_args()
    sys.exit(asyncio.run(_main_async(args.date, args.lenient_on_scope_mismatch)))


if __name__ == "__main__":
    main()
