from __future__ import annotations

from pathlib import Path

from auditwalk.cli.dispatch import Invocation


_PROFILE_CONFIG = {
    "quick": {"hours": 4, "max_results": 100},
    "full": {"hours": 24, "max_results": 400},
    "paranoid": {"hours": 168, "max_results": 2000},
}


def _run_scan_profile(profile: str, inv: Invocation) -> int:
    # Lazy import keeps `auditwalk --help` resilient even in partial environments.
    from modules.filesystem import scan_recent_changes
    from modules.report import print_table, write_json_report

    cfg = _PROFILE_CONFIG[profile]
    roots = inv.opts.get("roots") or [str(Path.home())]
    exclude = inv.opts.get("exclude") or []
    follow_symlinks = bool(inv.opts.get("follow_symlinks"))
    report_dir = inv.opts.get("report_dir") or str(Path.cwd() / "reports")
    no_report = bool(inv.opts.get("no_report"))

    changes = scan_recent_changes(
        roots=roots,
        hours=cfg["hours"],
        max_results=cfg["max_results"],
        follow_symlinks=follow_symlinks,
        exclude_dirs=exclude,
    )

    print(f"\nAuditWalk Scan ({profile})\n")
    rows = [{"mtime": c.mtime_iso, "size": c.size_bytes, "path": c.path} for c in changes]
    print_table(rows, columns=["mtime", "size", "path"], limit=30)

    if not no_report:
        out = write_json_report(report_dir, f"scan_{profile}", changes)
        print(f"\nReport written: {out}")
    return 0


def scan_quick(inv: Invocation) -> int:
    return _run_scan_profile("quick", inv)


def scan_full(inv: Invocation) -> int:
    return _run_scan_profile("full", inv)


def scan_paranoid(inv: Invocation) -> int:
    return _run_scan_profile("paranoid", inv)
