"""

All data is fabricated for a portfolio demonstration; this is not a real incident.
Run from the project root:
    python analysis/analyze_auth_logs.py
Requires pandas: python -m pip install pandas
"""
from pathlib import Path
import json
import pandas as pd

ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data" / "synthetic_authentication_events.csv"
OUT = ROOT / "files"
OUT.mkdir(exist_ok=True)

df = pd.read_csv(DATA, parse_dates=["timestamp_utc"])
df["source_ip"] = df["source_ip"].astype(str)

# Illustrative heuristics, not proof of compromise.
failed_by_ip = df[df["auth_result"].eq("failure")].groupby("source_ip").agg(
    failed_attempts=("auth_result", "size"),
    targeted_accounts=("user", "nunique")
).reset_index()
spray_candidates = failed_by_ip[
    (failed_by_ip["failed_attempts"] >= 20) &
    (failed_by_ip["targeted_accounts"] >= 5)
].copy()
spray_candidates["finding"] = "Repeated failures across multiple accounts"
spray_candidates["priority"] = "High"

unusual_location = df[
    df["scenario_tag"].eq("unusual_location_simulation") &
    df["auth_result"].eq("success")
].copy()
unusual_location["finding"] = "Successful sign-in from an unusual synthetic location"
unusual_location["priority"] = "Medium"

legacy = df[
    df["scenario_tag"].eq("legacy_auth_simulation") &
    df["mfa_result"].eq("not_required")
].copy()
legacy["finding"] = "Legacy-style authentication without MFA challenge"
legacy["priority"] = "High"

privileged = df[
    df["user"].str.startswith("admin") &
    df["auth_result"].eq("success") &
    df["mfa_result"].eq("not_required")
].copy()
privileged["finding"] = "Privileged successful sign-in without MFA"
privileged["priority"] = "Critical"

findings = []
for _, r in spray_candidates.iterrows():
    findings.append({
        "finding": r["finding"], "priority": r["priority"],
        "count_or_scope": int(r["failed_attempts"]),
        "evidence": f'{int(r["failed_attempts"])} failures across {int(r["targeted_accounts"])} accounts from {r["source_ip"]}',
        "recommended_action": "Review source and targeted accounts; tune identity-provider detection; enforce smart lockout and phishing-resistant MFA."
    })
for label, subset, priority, action in [
    ("Successful sign-in from an unusual synthetic location", unusual_location, "Medium",
     "Validate against user travel, VPN, and device context before escalation."),
    ("Legacy-style authentication without MFA challenge", legacy, "High",
     "Inventory legacy protocols and disable them where business compatibility permits."),
    ("Privileged successful sign-in without MFA", privileged, "Critical",
     "Require MFA for all privileged access and investigate the affected sessions.")
]:
    findings.append({
        "finding": label, "priority": priority, "count_or_scope": int(len(subset)),
        "evidence": f"{len(subset)} synthetic events matched the scenario rule",
        "recommended_action": action
    })

findings_df = pd.DataFrame(findings)
findings_df.to_csv(OUT / "triage_findings.csv", index=False)

summary = {
    "dataset_scope": "Synthetic authentication events only",
    "total_events": int(len(df)),
    "unique_users": int(df["user"].nunique()),
    "failed_events": int(df["auth_result"].eq("failure").sum()),
    "successful_events": int(df["auth_result"].eq("success").sum()),
    "events_without_mfa_challenge": int(df["mfa_result"].eq("not_required").sum() + df["mfa_result"].eq("not_triggered").sum()),
    "unmanaged_device_events": int(df["device_managed"].eq("no").sum()),
    "scenario_tag_counts": {str(k): int(v) for k, v in df["scenario_tag"].value_counts().items()},
    "important_limit": "Scenario tags are included to make the synthetic dataset auditable. They are not independent proof that a real attack occurred."
}
(OUT / "analysis_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
print(json.dumps(summary, indent=2))
print(f"\nWrote {OUT / 'triage_findings.csv'}")
