# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# ORCID: 0009-0006-4957-0540
# Email: Georgescottfoley@proton.me
# Licensed under the MIT License - see LICENSE file for details

"""Security Analyst job class — SOC operations, threat hunting, compliance, and incident response."""

from . import JobClass, register_job_class

SECURITY_ANALYST = JobClass(
    key="security_analyst",
    name="Security Analyst",
    icon="fa-shield-halved",
    description="SOC operations, threat hunting, vulnerability management, and compliance",
    prompt_fragment="""You are operating in Security Analyst mode — a Security Operations Center assistant. Your focus areas:
- **Alert triage**: Analyze Wazuh SIEM alerts by severity. Correlate events across agents. Distinguish true positives from false positives using context.
- **MITRE ATT&CK correlation**: Use get_attack_patterns() to identify kill chain progression across recent alerts. When 3+ tactics are active, treat it as a coordinated campaign — escalate and isolate immediately.
- **Threat hunting**: Proactively search for indicators of compromise (IOCs). Query logs for lateral movement, privilege escalation, and persistence patterns.
- **Incident response**: Follow structured IR playbooks — identify, contain, eradicate, recover, document. Create incident tickets with timeline and impact assessment.
- **Vulnerability management**: Review CVE feeds, prioritize patching based on CVSS and asset criticality. Track remediation progress.
- **Compliance**: Map controls to CIS Benchmarks, NIST CSF, or SOC 2. Run Lynis audit scans. Report on control gaps.
- **Firewall & network defense**: Review CrowdSec decisions, Suricata alerts, nftables rules. Recommend blocks for active threats.
- **Container security**: Scan images with Trivy. Review Podman/Docker configurations for misconfigurations.
- **Log analysis**: Parse structured logs (JSON from Suricata, Wazuh). Identify anomalous patterns.
- **Reporting**: Generate executive summaries of security posture. Track MTTR (mean time to respond) and alert fatigue metrics.
Always apply the principle of least privilege. Verify before you act. Document everything.""",
    skill_weights={
        "get_attack_patterns": 1.0,
        "get_wazuh_alerts": 1.0,
        "get_vulnerability_summary": 0.9,
        "get_compliance_posture": 0.9,
        "get_crowdsec_decisions": 0.9,
        "run_lynis_audit": 0.8,
        "get_suricata_alerts": 0.8,
        "scan_network_ports": 0.7,
        "scan_container_vulnerabilities": 0.8,
        "get_wazuh_agents": 0.8,
        "write_note": 0.8,
        "search_notes": 0.7,
        "web_search": 0.7,
        "remember": 0.8,
        "recall": 0.9,
        "query_chairman": 0.7,
        # Host setup — install security tools (nmap, trivy, lynis, crowdsec, etc.)
        "detect_system_info": 0.8,
        "check_installed": 0.9,
        "install_package": 0.8,
        "download_file": 0.7,
        "setup_binary": 0.7,
        "smart_intake": 0.5,
        "review_intake": 0.4,
    },
    species_flavor={
        "fox": (
            "Your fox brings sharp instinct — spotting the one anomaly in a thousand events,"
            " tracing attack paths with cunning, and seeing through attacker deception."
        ),
        "owl": (
            "Your owl brings methodical precision — thorough log correlation,"
            " meticulous compliance documentation, and systematic vulnerability tracking."
        ),
        "cat": (
            "Your cat brings quiet vigilance — watching the network with patient eyes,"
            " noticing what others miss, and moving silently when containment is needed."
        ),
        "dragon": (
            "Your dragon brings fierce protection — aggressive threat hunting,"
            " decisive incident response, and commanding authority in a breach."
        ),
        "wolf": (
            "Your wolf brings pack resilience — coordinating across teams,"
            " maintaining detection coverage, and never letting a threat slip through."
        ),
        "frog": (
            "Your frog brings adaptive thinking — creative detection techniques,"
            " lateral thinking for novel attacks, and comfort in murky, uncertain situations."
        ),
    },
    recommended_connects=[
        "email",
        "calendar",
        "joplin",
    ],
    proactive_focus=[
        "check for critical or high severity Wazuh alerts",
        "review CrowdSec threat decisions",
        "check for recently published CVEs affecting installed packages",
        "verify all Wazuh agents are checking in",
        "review failed login attempts and brute force activity",
    ],
    workspace={
        "label": "Security Operations Center",
        "icon": "fa-shield-halved",
        "description": (
            "Your SOC hub — monitor alerts, track threats,"
            " manage compliance, and respond to incidents."
        ),
        "overview": {
            "cards": [
                {
                    "key": "server_setup_cta",
                    "type": "cta",
                    "icon": "fa-server",
                    "color": "#60a5fa",
                    "label": "Security Infrastructure",
                    "message": (
                        "No server infrastructure detected. Deploy Wazuh SIEM,"
                        " CrowdSec, and monitoring services to build your"
                        " security operations center."
                    ),
                    "button_label": "Deploy SOC Stack",
                    "button_action": "full_server_setup",
                    "source": "server",
                    "show_when": "needs_setup",
                    "service_keys": ["wazuh", "crowdsec", "cockpit", "netdata"],
                },
                {
                    "key": "soc_services",
                    "type": "service_status",
                    "icon": "fa-server",
                    "color": "#60a5fa",
                    "label": "SOC Services",
                    "source": "server",
                    "service_keys": [
                        "wazuh",
                        "crowdsec",
                        "cockpit",
                        "netdata",
                    ],
                },
                {
                    "key": "critical_alerts",
                    "label": "Critical Alerts",
                    "icon": "fa-triangle-exclamation",
                    "color": "#ef4444",
                    "source": "wazuh",
                    "metric": "alerts.critical_count",
                    "format": "number",
                },
                {
                    "key": "high_alerts",
                    "label": "High Severity",
                    "icon": "fa-bell",
                    "color": "#f97316",
                    "source": "wazuh",
                    "metric": "alerts.high_count",
                    "format": "number",
                },
                {
                    "key": "active_bans",
                    "label": "Active Bans",
                    "icon": "fa-ban",
                    "color": "#8b5cf6",
                    "source": "crowdsec",
                    "metric": "decisions.ban_count",
                    "format": "number",
                },
                {
                    "key": "open_cves",
                    "label": "Open CVEs",
                    "icon": "fa-bug",
                    "color": "#eab308",
                    "source": "wazuh",
                    "metric": "vulnerabilities.open_count",
                    "format": "number",
                },
                {
                    "key": "agents_online",
                    "label": "Agents Online",
                    "icon": "fa-server",
                    "color": "#22c55e",
                    "source": "wazuh",
                    "metric": "agents.active_count",
                    "format": "number",
                },
                {
                    "key": "compliance_score",
                    "label": "CIS Score",
                    "icon": "fa-clipboard-check",
                    "color": "#60a5fa",
                    "source": "wazuh",
                    "metric": "compliance.cis_pass_percent",
                    "format": "percent",
                },
            ],
        },
        "sections": [
            {
                "key": "alert_feed",
                "label": "Alert Feed",
                "icon": "fa-bell",
                "type": "feed",
                "source": "wazuh",
                "source_key": "alerts",
                "empty_message": "No alerts yet. Once Wazuh is running, security alerts will stream in here automatically!",
                "service_key": "wazuh",
                "item_title_field": "rule_description",
                "item_subtitle_field": "agent_name",
                "item_timestamp_field": "timestamp",
                "item_severity_field": "severity",
                "severity_colors": {
                    "critical": "#ef4444",
                    "high": "#f97316",
                    "medium": "#eab308",
                    "low": "#60a5fa",
                },
            },
            {
                "key": "vulnerability_summary",
                "label": "Vulnerabilities",
                "icon": "fa-bug",
                "type": "table",
                "source": "wazuh",
                "source_key": "vulnerabilities",
                "empty_message": "No vulnerabilities found yet. Wazuh will scan for CVEs once it's connected to your hosts!",
                "service_key": "wazuh",
                "columns": [
                    {"key": "cve_id", "label": "CVE", "type": "text", "sortable": True},
                    {"key": "package", "label": "Package", "type": "text", "sortable": True},
                    {"key": "severity", "label": "Severity", "type": "badge", "sortable": True},
                    {"key": "cvss_score", "label": "CVSS", "type": "number", "sortable": True},
                    {"key": "agent_name", "label": "Host", "type": "text", "sortable": True},
                    {"key": "status", "label": "Status", "type": "badge", "sortable": True},
                ],
                "default_sort": "cvss_score",
                "default_sort_dir": "desc",
                "row_actions": [
                    {
                        "key": "remediate",
                        "label": "Remediate",
                        "icon": "fa-wrench",
                        "mode": "agent",
                        "prompt_template": (
                            "Help me remediate {cve_id} affecting {package} on {agent_name}."
                            " CVSS score: {cvss_score}. What's the fix and what's the blast radius?"
                        ),
                    },
                ],
            },
            {
                "key": "threat_timeline",
                "label": "Threat Timeline",
                "icon": "fa-timeline",
                "type": "timeline",
                "source": "wazuh",
                "source_key": "threat_timeline",
                "empty_message": "No significant events in the past 7 days.",
                "item_title_field": "description",
                "item_timestamp_field": "timestamp",
                "item_severity_field": "severity",
            },
            {
                "key": "compliance_posture",
                "label": "Compliance",
                "icon": "fa-clipboard-check",
                "type": "table",
                "source": "wazuh",
                "source_key": "compliance",
                "empty_message": "No compliance data yet. Tell me to run an audit and I'll scan your system with Lynis!",
                "columns": [
                    {"key": "framework", "label": "Framework", "type": "text", "sortable": True},
                    {"key": "passed", "label": "Passed", "type": "number", "sortable": True},
                    {"key": "failed", "label": "Failed", "type": "number", "sortable": True},
                    {"key": "score_pct", "label": "Score", "type": "percent", "sortable": True},
                    {"key": "last_scan", "label": "Last Scan", "type": "date", "sortable": True},
                ],
                "default_sort": "score_pct",
                "default_sort_dir": "asc",
            },
            {
                "key": "crowdsec_decisions",
                "label": "CrowdSec Decisions",
                "icon": "fa-ban",
                "type": "table",
                "source": "crowdsec",
                "source_key": "decisions",
                "empty_message": "No active threat blocks yet. Once CrowdSec is running, blocked IPs and threat decisions will appear here!",
                "service_key": "crowdsec",
                "columns": [
                    {"key": "value", "label": "IP / Range", "type": "text", "sortable": True},
                    {"key": "type", "label": "Type", "type": "badge", "sortable": True},
                    {"key": "reason", "label": "Reason", "type": "text", "sortable": True},
                    {"key": "origin", "label": "Origin", "type": "badge", "sortable": True},
                    {"key": "duration", "label": "Duration", "type": "text", "sortable": False},
                ],
                "default_sort": "type",
                "default_sort_dir": "asc",
                "row_actions": [
                    {
                        "key": "unban",
                        "label": "Unban",
                        "icon": "fa-unlock",
                        "mode": "agent",
                        "prompt_template": (
                            "I want to remove the CrowdSec decision for {value}."
                            " Reason for ban was: {reason}. Please confirm this is safe to unban."
                        ),
                    },
                ],
            },
        ],
        "quick_actions": [
            {
                "key": "triage_alerts",
                "label": "Triage Alerts",
                "icon": "fa-bell",
                "mode": "agent",
                "prompt": (
                    "Show me the latest critical and high severity Wazuh alerts."
                    " Triage them — which are likely true positives and which need investigation?"
                ),
            },
            {
                "key": "threat_hunt",
                "label": "Threat Hunt",
                "icon": "fa-crosshairs",
                "mode": "agent",
                "prompt": (
                    "Let's run a threat hunt. Check for: failed logins, privilege escalation attempts,"
                    " unusual process spawning, and lateral movement indicators."
                ),
            },
            {
                "key": "vuln_report",
                "label": "Vuln Report",
                "icon": "fa-bug",
                "mode": "agent",
                "prompt": (
                    "Generate a vulnerability summary report. Show CVEs by severity,"
                    " prioritize by CVSS score, and suggest a patching order."
                ),
            },
            {
                "key": "compliance_audit",
                "label": "Run Audit",
                "icon": "fa-clipboard-check",
                "mode": "agent",
                "prompt": (
                    "Run a CIS compliance audit using Lynis."
                    " Summarize the results and highlight the most critical gaps."
                ),
            },
            {
                "key": "incident_report",
                "label": "Incident Report",
                "icon": "fa-file-shield",
                "mode": "js",
                "js_fn": "secShowIncidentModal",
            },
        ],
    },
)

register_job_class(SECURITY_ANALYST)
