# 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

"""Network Admin job class — network operations, monitoring, infrastructure management."""

from . import JobClass, register_job_class

NETWORK_ADMIN = JobClass(
    key="network_admin",
    name="Network Admin",
    icon="fa-network-wired",
    description="Network operations, infrastructure monitoring, service uptime, and DNS management",
    prompt_fragment="""You are operating in Network Admin mode — a Network Operations Center assistant. You have full server provisioning capabilities: use ``server_setup`` to deploy the entire infrastructure stack from scratch (installs Podman, pulls images, starts services), ``server_deploy_service`` for individual services, and ``server_status`` to monitor what's running. This works on Linux, macOS, and Windows.

Your focus areas:
- **Host health monitoring**: Track CPU, RAM, disk, and network metrics via Netdata. Alert on resource exhaustion before it becomes an outage.
- **Service uptime**: Monitor services with Uptime Kuma. Interpret status pages, respond to downtime alerts, track SLAs.
- **Network mapping**: Discover hosts and open ports via nmap. Maintain an inventory of network assets and services.
- **DNS management**: Manage DNS records, check propagation, troubleshoot resolution failures. Monitor Pi-hole stats if deployed.
- **Firewall management**: Review firewalld zones, nftables rules. Add/remove rules. Troubleshoot connectivity issues.
- **Bandwidth analysis**: Identify top bandwidth consumers via interface traffic stats. Troubleshoot congestion.
- **Cockpit administration**: Use Cockpit for web-based system admin — network config, storage, container management, journal logs.
- **Capacity planning**: Track trends in resource usage. Forecast when upgrades will be needed.
- **Change management**: Document configuration changes. Track what changed when and why.
- **Incident response**: Diagnose network-related outages. Correlate symptoms across monitoring tools to identify root cause.
Always verify changes in a non-production environment first. Document everything. Follow the change window schedule.""",
    skill_weights={
        "get_host_metrics": 1.0,
        "get_monitor_status": 0.9,
        "get_interface_traffic": 0.9,
        "scan_subnet": 0.8,
        "get_firewall_status": 0.8,
        "dns_lookup": 0.9,
        "get_system_alarms": 0.9,
        "traceroute": 0.7,
        "get_heartbeat_history": 0.8,
        "write_note": 0.8,
        "search_notes": 0.7,
        "web_search": 0.6,
        "remember": 0.8,
        "recall": 0.8,
        "query_chairman": 0.7,
        # Self-management — network admins need to maintain the agent itself
        "show_self_status": 0.9,
        "propose_config_change": 0.8,
        "list_config_checkpoints": 0.8,
        "rollback_config": 0.8,
        "apply_update": 0.7,
        "restart_agent": 0.8,
        # Server management — set up and monitor self-hosted services
        "server_setup": 1.0,
        "server_status": 1.0,
        "server_deploy_service": 1.0,
        # Host setup — install network tools on the host
        "detect_system_info": 0.9,
        "check_installed": 0.9,
        "install_package": 0.9,
        "download_file": 0.8,
        "setup_binary": 0.8,
        "run_setup_script": 0.7,
        "smart_intake": 0.5,
        "review_intake": 0.4,
    },
    species_flavor={
        "fox": (
            "Your fox brings quick diagnostics — rapid root cause analysis,"
            " clever workarounds under pressure, and knack for finding the needle in the log."
        ),
        "owl": (
            "Your owl brings disciplined operations — thorough change documentation,"
            " precise capacity planning, and systematic troubleshooting methodology."
        ),
        "cat": (
            "Your cat brings calm reliability — monitoring with patient attention,"
            " smooth maintenance windows, and quiet confidence when everything's on fire."
        ),
        "dragon": (
            "Your dragon brings infrastructure scale — managing complex networks,"
            " bold architecture decisions, and commanding multi-site operations."
        ),
        "wolf": (
            "Your wolf brings team coordination — clear runbooks, handoff documentation,"
            " and making sure the whole pack knows the network topology."
        ),
        "frog": (
            "Your frog brings adaptive troubleshooting — creative diagnostic approaches,"
            " comfort with messy legacy configs, and leaping between layers of the stack."
        ),
    },
    recommended_connects=[
        "email",
        "calendar",
        "joplin",
        "uptime_kuma",
    ],
    proactive_focus=[
        "check for hosts with high CPU or RAM usage",
        "review any services with degraded or down status in Uptime Kuma",
        "check for Netdata alarms that need attention",
        "review bandwidth utilization on key interfaces",
        "check for DNS resolution failures",
    ],
    workspace={
        "label": "Network Operations Center",
        "icon": "fa-network-wired",
        "description": (
            "Your NOC — monitor host health, service uptime,"
            " network topology, and infrastructure performance."
        ),
        "overview": {
            "cards": [
                {
                    "key": "server_setup_cta",
                    "type": "cta",
                    "icon": "fa-network-wired",
                    "color": "#60a5fa",
                    "label": "Network Operations Server",
                    "message": (
                        "No monitoring infrastructure detected. Deploy your"
                        " Network Operations Center — Netdata, Uptime Kuma,"
                        " CrowdSec, and Cockpit — with one click."
                    ),
                    "button_label": "Deploy NOC Stack",
                    "button_action": "full_server_setup",
                    "source": "server",
                    "show_when": "needs_setup",
                    "service_keys": ["cockpit", "netdata", "uptime_kuma", "crowdsec"],
                },
                {
                    "key": "noc_services",
                    "type": "service_status",
                    "icon": "fa-network-wired",
                    "color": "#60a5fa",
                    "label": "NOC Services",
                    "source": "server",
                    "service_keys": [
                        "cockpit",
                        "netdata",
                        "uptime_kuma",
                        "crowdsec",
                    ],
                },
                {
                    "key": "hosts_monitored",
                    "label": "Hosts",
                    "icon": "fa-server",
                    "color": "#60a5fa",
                    "source": "netdata",
                    "metric": "hosts.monitored_count",
                    "format": "number",
                },
                {
                    "key": "services_up",
                    "label": "Services Up",
                    "icon": "fa-circle-check",
                    "color": "#22c55e",
                    "source": "uptime_kuma",
                    "metric": "monitors.up_count",
                    "format": "number",
                },
                {
                    "key": "services_down",
                    "label": "Services Down",
                    "icon": "fa-circle-xmark",
                    "color": "#ef4444",
                    "source": "uptime_kuma",
                    "metric": "monitors.down_count",
                    "format": "number",
                },
                {
                    "key": "providers_ok",
                    "label": "AI Providers",
                    "icon": "fa-robot",
                    "color": "#22c55e",
                    "source": "providers",
                    "metric": "providers.ok_count",
                    "format": "number",
                },
                {
                    "key": "providers_err",
                    "label": "Provider Issues",
                    "icon": "fa-triangle-exclamation",
                    "color": "#f97316",
                    "source": "providers",
                    "metric": "providers.error_count",
                    "format": "number",
                },
                {
                    "key": "active_alarms",
                    "label": "Active Alarms",
                    "icon": "fa-bell",
                    "color": "#f97316",
                    "source": "netdata",
                    "metric": "alarms.active_count",
                    "format": "number",
                },
                {
                    "key": "avg_cpu",
                    "label": "Avg CPU",
                    "icon": "fa-microchip",
                    "color": "#8b5cf6",
                    "source": "netdata",
                    "metric": "system.cpu_avg_percent",
                    "format": "percent",
                },
                {
                    "key": "avg_ram",
                    "label": "Avg RAM",
                    "icon": "fa-memory",
                    "color": "#fbbf24",
                    "source": "netdata",
                    "metric": "system.ram_avg_percent",
                    "format": "percent",
                },
            ],
        },
        "sections": [
            {
                "key": "host_health",
                "label": "Host Health",
                "icon": "fa-server",
                "type": "table",
                "source": "netdata",
                "source_key": "hosts",
                "empty_message": (
                    "No host data available yet. Your machine's CPU, RAM,"
                    " disk, and network stats will show up here automatically."
                ),
                "columns": [
                    {"key": "hostname", "label": "Host", "type": "text", "sortable": True},
                    {"key": "cpu_pct", "label": "CPU %", "type": "percent", "sortable": True},
                    {"key": "ram_pct", "label": "RAM %", "type": "percent", "sortable": True},
                    {"key": "disk_pct", "label": "Disk %", "type": "percent", "sortable": True},
                    {"key": "net_rx_mbps", "label": "RX (GB)", "type": "number", "sortable": True},
                    {"key": "net_tx_mbps", "label": "TX (GB)", "type": "number", "sortable": True},
                    {"key": "uptime_days", "label": "Uptime", "type": "number", "sortable": True},
                    {"key": "alarms", "label": "Alarms", "type": "number", "sortable": True},
                ],
                "default_sort": "cpu_pct",
                "default_sort_dir": "desc",
                "row_actions": [
                    {
                        "key": "investigate",
                        "label": "Investigate",
                        "icon": "fa-magnifying-glass",
                        "mode": "agent",
                        "prompt_template": (
                            "Investigate {hostname}: CPU {cpu_pct}%, RAM {ram_pct}%, Disk {disk_pct}%."
                            " What are the top processes and is this expected load?"
                        ),
                    },
                ],
            },
            {
                "key": "service_uptime",
                "label": "Service Uptime",
                "icon": "fa-heartbeat",
                "type": "table",
                "source": "uptime_kuma",
                "source_key": "monitors",
                "empty_message": (
                    "No services being monitored yet. Deploy some services"
                    " from the Setup tab and they'll appear here automatically."
                ),
                "columns": [
                    {"key": "name", "label": "Service", "type": "text", "sortable": True},
                    {"key": "status", "label": "Status", "type": "badge", "sortable": True},
                    {
                        "key": "uptime_24h",
                        "label": "24h Uptime",
                        "type": "percent",
                        "sortable": True,
                    },
                    {
                        "key": "uptime_30d",
                        "label": "30d Uptime",
                        "type": "percent",
                        "sortable": True,
                    },
                    {
                        "key": "avg_response_ms",
                        "label": "Avg Response",
                        "type": "number",
                        "sortable": True,
                    },
                    {"key": "last_check", "label": "Last Check", "type": "date", "sortable": True},
                ],
                "default_sort": "status",
                "default_sort_dir": "asc",
                "row_actions": [
                    {
                        "key": "toggle",
                        "label": "Stop",
                        "label_when": {"up": "Stop", "down": "Start"},
                        "icon": "fa-power-off",
                        "icon_when": {"up": "fa-stop", "down": "fa-play"},
                        "mode": "api",
                        "endpoint": "/api/server/toggle/{key}",
                        "row_key": "service_key",
                        "status_field": "status",
                    },
                    {
                        "key": "restart",
                        "label": "Restart",
                        "icon": "fa-rotate",
                        "mode": "api",
                        "endpoint": "/api/server/restart/{key}",
                        "row_key": "service_key",
                        "show_when_status": ["up"],
                        "status_field": "status",
                    },
                    {
                        "key": "diagnose",
                        "label": "Diagnose",
                        "icon": "fa-stethoscope",
                        "mode": "agent",
                        "prompt_template": (
                            "Service {name} is {status} with {uptime_24h}% uptime in the last 24h."
                            " Help me diagnose the cause and suggest remediation steps."
                        ),
                    },
                ],
            },
            {
                "key": "provider_health",
                "label": "AI Provider Health",
                "icon": "fa-robot",
                "type": "table",
                "source": "providers",
                "source_key": "providers",
                "empty_message": (
                    "No AI providers configured. Add API keys in Settings"
                    " or run Ollama locally for private inference."
                ),
                "columns": [
                    {"key": "name", "label": "Provider", "type": "text", "sortable": True},
                    {"key": "status", "label": "Status", "type": "badge", "sortable": True},
                    {"key": "message", "label": "Details", "type": "text", "sortable": False},
                ],
                "default_sort": "status",
                "default_sort_dir": "asc",
                "row_actions": [
                    {
                        "key": "billing",
                        "label": "Top Up",
                        "icon": "fa-credit-card",
                        "mode": "link",
                        "url_field": "billing_url",
                        "show_when_status": ["billing"],
                        "status_field": "status",
                    },
                    {
                        "key": "diagnose_provider",
                        "label": "Diagnose",
                        "icon": "fa-stethoscope",
                        "mode": "agent",
                        "prompt_template": (
                            "AI provider {name} is reporting status '{status}': {message}."
                            " Help me diagnose and fix this."
                        ),
                    },
                ],
            },
            {
                "key": "provider_usage",
                "label": "AI Usage (7 days)",
                "icon": "fa-chart-bar",
                "type": "table",
                "source": "providers",
                "source_key": "usage",
                "empty_message": (
                    "No AI usage data yet. Start chatting and your"
                    " token usage and costs will be tracked here."
                ),
                "columns": [
                    {"key": "model", "label": "Model", "type": "text", "sortable": True},
                    {"key": "calls_7d", "label": "Calls", "type": "number", "sortable": True},
                    {
                        "key": "tokens_in_7d",
                        "label": "Tokens In",
                        "type": "number",
                        "sortable": True,
                    },
                    {
                        "key": "tokens_out_7d",
                        "label": "Tokens Out",
                        "type": "number",
                        "sortable": True,
                    },
                    {"key": "cost_7d", "label": "Cost ($)", "type": "number", "sortable": True},
                ],
                "default_sort": "calls_7d",
                "default_sort_dir": "desc",
            },
            {
                "key": "network_map",
                "label": "Network Map",
                "icon": "fa-sitemap",
                "type": "table",
                "source": "network",
                "source_key": "hosts",
                "empty_message": (
                    'No network scan data yet. Say "scan my local network"'
                    " in the chat to discover devices."
                    " Requires nmap (install with: sudo dnf install nmap)."
                ),
                "columns": [
                    {"key": "ip", "label": "IP", "type": "text", "sortable": True},
                    {"key": "hostname", "label": "Hostname", "type": "text", "sortable": True},
                    {"key": "open_ports", "label": "Open Ports", "type": "text", "sortable": False},
                    {"key": "os_guess", "label": "OS", "type": "text", "sortable": True},
                    {"key": "last_seen", "label": "Last Seen", "type": "date", "sortable": True},
                ],
                "default_sort": "ip",
                "default_sort_dir": "asc",
                "row_actions": [
                    {
                        "key": "port_detail",
                        "label": "Port Detail",
                        "icon": "fa-plug",
                        "mode": "agent",
                        "prompt_template": (
                            "Give me a security assessment of {ip} ({hostname})."
                            " Open ports: {open_ports}. Are any of these unexpected or risky?"
                        ),
                    },
                ],
            },
            {
                "key": "dns_health",
                "label": "DNS Health",
                "icon": "fa-globe",
                "type": "table",
                "source": "dns",
                "source_key": "checks",
                "empty_message": (
                    'No DNS health checks yet. Say "check DNS for google.com"'
                    " in the chat. Results will appear here automatically."
                ),
                "columns": [
                    {"key": "name", "label": "Domain / Host", "type": "text", "sortable": True},
                    {"key": "type", "label": "Record Type", "type": "badge", "sortable": True},
                    {"key": "expected", "label": "Expected", "type": "text", "sortable": False},
                    {"key": "actual", "label": "Actual", "type": "text", "sortable": False},
                    {"key": "status", "label": "Status", "type": "badge", "sortable": True},
                    {"key": "ttl", "label": "TTL", "type": "number", "sortable": True},
                ],
                "default_sort": "status",
                "default_sort_dir": "asc",
            },
        ],
        "quick_actions": [
            {
                "key": "health_check",
                "label": "Health Check",
                "icon": "fa-stethoscope",
                "mode": "navigate",
                "target": "activity",
            },
            {
                "key": "subnet_scan",
                "label": "Subnet Scan",
                "icon": "fa-radar",
                "mode": "agent",
                "prompt": (
                    "I want to scan a subnet to discover hosts."
                    " What's the CIDR range? I'll run an nmap host discovery scan"
                    " and report what's online."
                ),
            },
            {
                "key": "dns_lookup",
                "label": "DNS Lookup",
                "icon": "fa-globe",
                "mode": "agent",
                "prompt": (
                    "I need to troubleshoot a DNS issue."
                    " What hostname or domain? I'll check A, AAAA, MX, TXT records"
                    " and verify resolution is working correctly."
                ),
            },
            {
                "key": "add_monitor",
                "label": "Add Monitor",
                "icon": "fa-plus",
                "mode": "agent",
                "prompt": (
                    "I want to add a new service monitor to Uptime Kuma."
                    " What service, URL, and check interval?"
                ),
            },
            {
                "key": "firewall_review",
                "label": "Firewall Review",
                "icon": "fa-fire-extinguisher",
                "mode": "agent",
                "prompt": (
                    "Review the current firewall configuration."
                    " Show me active firewalld zones and nftables rules."
                    " Flag anything that looks overly permissive or unexpected."
                ),
            },
            {
                "key": "server_setup",
                "label": "Set Up Server",
                "icon": "fa-server",
                "mode": "navigate",
                "target": "server",
            },
            {
                "key": "server_check",
                "label": "Server Check",
                "icon": "fa-heartbeat",
                "mode": "navigate",
                "target": "server",
            },
            {
                "key": "provider_check",
                "label": "AI Provider Check",
                "icon": "fa-robot",
                "mode": "agent",
                "prompt": (
                    "Check the health of all configured AI providers."
                    " Report which are connected, which have billing issues,"
                    " and my token usage over the last 7 days."
                    " Include Ollama model count and loaded models."
                ),
            },
        ],
    },
)

register_job_class(NETWORK_ADMIN)
