"""Helper script for security scan Robot Framework tests.

Used by robot/security_scan.robot to verify nox session configuration.
"""

from __future__ import annotations

import ast
import sys
from pathlib import Path


def verify_session_exists() -> None:
    """Verify that security_scan is defined as a nox session."""
    noxfile = Path("noxfile.py")
    if not noxfile.exists():
        print("ERROR: noxfile.py not found", file=sys.stderr)
        sys.exit(1)

    content = noxfile.read_text(encoding="utf-8")
    tree = ast.parse(content)

    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef) and node.name == "security_scan":
            # Verify it has the nox.session decorator
            for decorator in node.decorator_list:
                if isinstance(decorator, ast.Call):
                    func = decorator.func
                    if isinstance(func, ast.Attribute) and func.attr == "session":
                        print("security-scan-session-ok")
                        return
                elif (
                    isinstance(decorator, ast.Attribute) and decorator.attr == "session"
                ):
                    print("security-scan-session-ok")
                    return
            # Function found but no nox.session decorator
            print(
                "ERROR: security_scan function found but no @nox.session decorator",
                file=sys.stderr,
            )
            sys.exit(1)

    print("ERROR: security_scan function not found in noxfile.py", file=sys.stderr)
    sys.exit(1)


def main() -> None:
    """Route to the appropriate verification function."""
    if len(sys.argv) < 2:
        print("Usage: helper_security_scan.py <command>", file=sys.stderr)
        sys.exit(1)

    command = sys.argv[1]
    commands = {
        "verify-session-exists": verify_session_exists,
    }

    handler = commands.get(command)
    if handler is None:
        print(f"Unknown command: {command}", file=sys.stderr)
        sys.exit(1)

    handler()


if __name__ == "__main__":
    main()
