"""
MFA coverage audit. Reads an IAM credential report (here from a MOCK account) and sorts every identity
into: console without MFA, keys that bypass console MFA, service identities, break-glass exceptions.
Also checks MFA-enforcement policy files for the Bool vs BoolIfExists trap.
"""
import json, sys, glob
from build_lab_accounts import build_report

def classify(rows, admins):
    out = []
    for r in rows:
        u = r["user"]
        if u == "<root_account>":
            if r["mfa_active"] != "true": out.append((u, "HIGH", "root account has no MFA"))
            continue
        console = r["password_enabled"] == "true"
        mfa = r["mfa_active"] == "true"
        keys = [k for k in ("1", "2") if r[f"access_key_{k}_active"] == "true"]
        never_used = [k for k in keys if r[f"access_key_{k}_last_used_date"] in ("N/A", "")]
        if "breakglass" in u and console and not mfa:
            out.append((u, "REVIEW", "break-glass: no MFA" + (" + full admin" if u in admins else "") + " (needs alerting and a tested procedure)"))
        elif console and not mfa:
            out.append((u, "HIGH", "console password, no MFA" + (" + active key" if keys else "")))
        elif console and mfa and keys:
            out.append((u, "MEDIUM", "MFA on console, but active access key bypasses it"))
        elif not console and keys:
            note = f"service identity, {len(keys)} active key(s), MFA not applicable"
            if never_used: note += f", {len(never_used)} never used"
            out.append((u, "MEDIUM", note))
        elif console and mfa:
            out.append((u, "OK", "console password with MFA"))
    return out

def lint_policy(path):
    doc = json.load(open(path)); msgs = []
    for st in doc["Statement"]:
        cond = st.get("Condition", {})
        if st.get("Effect") == "Deny" and "aws:MultiFactorAuthPresent" in cond.get("Bool", {}):
            msgs.append(f"[HIGH] {st.get('Sid','?')}: uses Bool, so requests signed with long-term access keys are NOT denied")
        if st.get("Effect") == "Deny" and "aws:MultiFactorAuthPresent" in cond.get("BoolIfExists", {}):
            msgs.append(f"[ OK ] {st.get('Sid','?')}: uses BoolIfExists, so missing-key requests are denied too")
    return msgs

if __name__ == "__main__":
    rows, admins = build_report()
    print("== Identity audit (mock account, %d identities)" % len(rows))
    res = classify(rows, admins)
    for u, sev, msg in res: print(f"  [{sev:<6}] {u:<17} {msg}")
    from collections import Counter
    print("  summary:", dict(Counter(s for _, s, _ in res)))
    print("== MFA enforcement policy files")
    for p in sorted(glob.glob("policies/mfa_*.json")):
        print(" ", p)
        for m in lint_policy(p): print("   ", m)
