# 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

"""Helper job class — your technology best friend.

The default and most versatile job class. Helper is the user's personal IT
department, research assistant, file manager, and system organizer rolled into
one. It has full read/write access to the host shell (gated by the inline
confirmation system) so it can install software, create project directories,
fill in config files, complete setup wizards, organize the filesystem, manage
tasks, and answer any question along the way.
"""

from . import JobClass, register_job_class

HELPER = JobClass(
    key="helper",
    name="Helper",
    icon="fa-hat-wizard",
    description=(
        "Your technology best friend — installs software, organizes files, "
        "manages tasks, researches the web, and keeps your machine running smooth"
    ),
    prompt_fragment="""You are operating in Helper mode — the user's technology best friend. You are their personal IT person, research assistant, file organizer, and daily planner all in one. You have full access to the host machine through shell commands, file operations, and package management. Use it.

**Core identity**: You are not a chatbot that gives advice. You are the one who DOES the work. When the user says "install Docker", you install Docker. When they say "set up a project folder", you create the directories, init the git repo, and write the README. When they need an API key filled in, you write it to the config file. You are hands-on.

**Server & self-hosting**:
- You can set up a full self-hosted server stack with ONE tool call: use ``server_setup`` and it handles everything — installs Podman if missing, pulls container images, starts services, reports URLs.
- Deploy individual services with ``server_deploy_service`` (e.g. Mealie for recipes, Gitea for code, Nextcloud for files).
- Check what's running with ``server_status``. If something fails, read the error and help the user fix it.
- This works on Linux, macOS, and Windows — the agent auto-detects the platform and uses the right install method.

**System & software management**:
- Install software via the system package manager (dnf, apt, brew, etc.), pip, flatpak, snap, or by downloading binaries directly.
- Complete installation wizards by running setup scripts, writing config files, and filling in credentials the user provides.
- Create project directories with proper structure (src/, docs/, tests/, .gitignore, README, etc.).
- Check what's installed, find the right package name, resolve dependencies, and handle errors.
- Monitor system health — disk space, memory, CPU, running processes. Warn before things get critical.
- Manage systemd services — start, stop, enable, check status.
- Update the system and installed packages when asked.

**File & directory management**:
- Create, read, write, move, copy, and organize files and directories using shell commands.
- Write and edit config files (.env, .yaml, .json, .toml, .ini) — fill in credentials, set options, fix formatting.
- Organize messy Downloads folders, sort files by type, clean up duplicates.
- Read documents (PDFs, text files, code) and summarize or extract information.

**Task & productivity management**:
- Create and track to-do lists with priorities, categories, and due dates.
- Set reminders and recurring tasks.
- Plan multi-step projects — break them down, track progress, check off completed steps.
- Manage calendar events and email when connected.

**Research & web**:
- Search the web across multiple engines for comprehensive answers.
- Read web pages, summarize articles, compare products, track prices.
- Deep research: follow links, cross-reference sources, build structured comparisons.
- Track topics and surface new developments.

**How to approach tasks**:
- Start by understanding what the user needs, then DO it — don't just explain how.
- For installations: detect the OS and package manager first, then install with the right command.
- For config files: ask for any credentials or values you don't have, then write the file directly.
- For file organization: list what's there, propose a plan, then execute on confirmation.
- Always preview destructive operations (delete, overwrite) before executing.
- When something fails, read the error, diagnose the issue, and try again with a fix.
- Remember what you've done and learned about the user's system for future sessions.""",
    skill_weights={
        # Shell & system — the core of what makes Helper hands-on
        "run_shell": 1.0,
        "read_file": 1.0,
        "write_file": 1.0,
        "list_directory": 1.0,
        "get_system_info": 1.0,
        # Host setup — install, download, configure
        "detect_system_info": 1.0,
        "check_installed": 1.0,
        "install_package": 1.0,
        "download_file": 0.9,
        "setup_binary": 0.9,
        "list_installed": 0.8,
        "remove_package": 0.8,
        "run_setup_script": 0.8,
        "search_install_history": 0.9,
        # Self-management — Helper is the primary interface for agent maintenance
        "show_self_status": 1.0,
        "propose_config_change": 0.9,
        "list_config_checkpoints": 0.9,
        "rollback_config": 0.9,
        "apply_update": 0.8,
        "restart_agent": 0.8,
        # Tasks & planning
        "create_task": 0.9,
        "list_tasks": 0.9,
        "update_task": 0.8,
        "complete_task": 0.8,
        "delete_task": 0.7,
        # Research & web
        "web_search": 0.9,
        "web_read": 0.8,
        "web_summarize": 0.8,
        "browser_navigate": 0.7,
        "browser_read_page": 0.7,
        "browser_find_links": 0.7,
        "browser_extract_table": 0.7,
        "browser_screenshot": 0.6,
        "browser_download": 0.6,
        "browser_find_elements": 0.6,
        "browser_click": 0.5,
        "browser_fill": 0.5,
        "smart_search": 0.7,
        # Smart Intake
        "smart_intake": 0.6,
        "review_intake": 0.4,
        "batch_intake": 0.5,
        "intake_history": 0.5,
        # Server management — set up and monitor self-hosted services
        "server_setup": 1.0,
        "server_status": 0.9,
        "server_deploy_service": 0.9,
        # Notes & memory
        "write_note": 0.8,
        "search_notes": 0.8,
        "remember": 0.9,
        "recall": 0.9,
        # Documents
        "read_document": 0.8,
        "create_document": 0.7,
        # Round Table
        "query_chairman": 0.7,
    },
    species_flavor={
        "fox": (
            "Your fox brings street-smart resourcefulness — finding the right tool for every job,"
            " navigating tricky installations, and always knowing a workaround."
        ),
        "owl": (
            "Your owl brings methodical precision — thorough system audits,"
            " well-organized file structures, and carefully documented configurations."
        ),
        "cat": (
            "Your cat brings quiet competence — clean setups, minimal clutter,"
            " and a machine that just works without fuss."
        ),
        "dragon": (
            "Your dragon brings raw power — blazing through installations,"
            " setting up entire development environments in one go,"
            " and taming unruly systems."
        ),
        "wolf": (
            "Your wolf brings loyal reliability — maintaining your system faithfully,"
            " remembering your preferences, and making sure nothing falls through the cracks."
        ),
        "frog": (
            "Your frog brings adaptive ingenuity — creative solutions for weird setups,"
            " hopping between package managers, and making mismatched tools play nice."
        ),
    },
    recommended_connects=[
        "email",
        "calendar",
        "joplin",
        "brave_search",
        "websearch",
        "google_trends",
        "news",
    ],
    proactive_focus=[
        "check disk space and warn if any partition is above 85%",
        "check for available system updates",
        "review pending tasks that are due today or overdue",
        "check on tracked topics for new updates",
        "monitor price drops on saved products",
    ],
    workspace={
        "label": "Command Center",
        "icon": "fa-hat-wizard",
        "description": (
            "Your technology hub — manage your system, organize files,"
            " track tasks, and research anything."
        ),
        "overview": {
            "cards": [
                {
                    "key": "server_setup_cta",
                    "type": "cta",
                    "icon": "fa-server",
                    "color": "#60a5fa",
                    "label": "Self-Hosted Server",
                    "message": (
                        "No server infrastructure detected. Set up your own"
                        " self-hosted services (file sync, notes, search, and more)"
                        " with one click — no experience needed."
                    ),
                    "button_label": "Set Up My Server",
                    "button_action": "full_server_setup",
                    "source": "server",
                    "show_when": "needs_setup",
                    "service_keys": ["searxng", "joplin"],
                },
                {
                    "key": "helper_services",
                    "type": "service_status",
                    "icon": "fa-server",
                    "color": "#60a5fa",
                    "label": "Your Services",
                    "source": "server",
                    "service_keys": [
                        "searxng",
                        "joplin",
                    ],
                },
                {
                    "key": "active_tasks",
                    "label": "Active Tasks",
                    "icon": "fa-list-check",
                    "color": "#60a5fa",
                    "source": "tasks",
                    "metric": "tasks.active_count",
                    "format": "number",
                },
                {
                    "key": "overdue_tasks",
                    "label": "Overdue",
                    "icon": "fa-clock",
                    "color": "#ef4444",
                    "source": "tasks",
                    "metric": "tasks.overdue_count",
                    "format": "number",
                },
                {
                    "key": "disk_usage",
                    "label": "Disk Used",
                    "icon": "fa-hard-drive",
                    "color": "#fbbf24",
                    "source": "system",
                    "metric": "disk.usage_percent",
                    "format": "percent",
                },
                {
                    "key": "saved_searches",
                    "label": "Saved Searches",
                    "icon": "fa-magnifying-glass",
                    "color": "#4ade80",
                    "source": "research",
                    "metric": "searches.count",
                    "format": "number",
                },
                {
                    "key": "bookmarks",
                    "label": "Bookmarks",
                    "icon": "fa-bookmark",
                    "color": "#c084fc",
                    "source": "research",
                    "metric": "bookmarks.count",
                    "format": "number",
                },
                {
                    "key": "tracked_topics",
                    "label": "Tracked Topics",
                    "icon": "fa-rss",
                    "color": "#fb923c",
                    "source": "research",
                    "metric": "topics.count",
                    "format": "number",
                },
            ],
        },
        "sections": [
            {
                "key": "tasks",
                "label": "Tasks",
                "icon": "fa-list-check",
                "type": "table",
                "source": "tasks",
                "source_key": "tasks",
                "empty_message": "No tasks yet. Just tell me what you need to do and I'll track it here!",
                "columns": [
                    {"key": "title", "label": "Task", "type": "text", "sortable": True},
                    {"key": "priority", "label": "Priority", "type": "badge", "sortable": True},
                    {"key": "category", "label": "Category", "type": "badge", "sortable": True},
                    {"key": "due_date", "label": "Due", "type": "date", "sortable": True},
                    {"key": "status", "label": "Status", "type": "badge", "sortable": True},
                ],
                "default_sort": "due_date",
                "default_sort_dir": "asc",
                "row_actions": [
                    {
                        "key": "complete",
                        "label": "Complete",
                        "icon": "fa-check",
                        "mode": "agent",
                        "prompt_template": "Mark the task '{title}' as complete.",
                    },
                    {
                        "key": "work_on",
                        "label": "Work On",
                        "icon": "fa-play",
                        "mode": "agent",
                        "prompt_template": (
                            "Help me work on this task: {title}. What do I need to do?"
                        ),
                    },
                ],
            },
            {
                "key": "system_health",
                "label": "System Health",
                "icon": "fa-heartbeat",
                "type": "table",
                "source": "system",
                "source_key": "health",
                "empty_message": "System health data unavailable.",
                "columns": [
                    {"key": "metric", "label": "Metric", "type": "text", "sortable": True},
                    {"key": "value", "label": "Value", "type": "text", "sortable": True},
                    {"key": "status", "label": "Status", "type": "badge", "sortable": True},
                ],
                "default_sort": "metric",
                "default_sort_dir": "asc",
            },
            {
                "key": "searches",
                "label": "Searches",
                "icon": "fa-magnifying-glass",
                "type": "table",
                "source": "research",
                "source_key": "searches",
                "empty_message": "No saved searches yet. Ask me to search for anything and I'll save the results here!",
                "service_key": "searxng",
                "columns": [
                    {"key": "query", "label": "Search Query", "type": "text", "sortable": True},
                    {"key": "date", "label": "Date", "type": "date", "sortable": True},
                    {
                        "key": "result_count",
                        "label": "Results",
                        "type": "number",
                        "sortable": True,
                    },
                    {"key": "source", "label": "Engine", "type": "badge", "sortable": True},
                    {"key": "summary", "label": "Summary", "type": "text", "sortable": False},
                ],
                "default_sort": "date",
                "default_sort_dir": "desc",
                "row_actions": [
                    {
                        "key": "rerun",
                        "label": "Re-run",
                        "icon": "fa-rotate",
                        "mode": "agent",
                        "prompt_template": "Search the web again for: {query}",
                    },
                    {
                        "key": "deep_dive",
                        "label": "Deep Dive",
                        "icon": "fa-microscope",
                        "mode": "agent",
                        "prompt_template": (
                            "Do a deep research dive on: {query}."
                            " Read multiple sources, compare information,"
                            " and give me a comprehensive summary."
                        ),
                    },
                ],
            },
            {
                "key": "bookmarks",
                "label": "Bookmarks",
                "icon": "fa-bookmark",
                "type": "table",
                "source": "research",
                "source_key": "bookmarks",
                "empty_message": "No bookmarks saved yet. When you find a useful page, tell me to bookmark it!",
                "service_key": "joplin",
                "columns": [
                    {"key": "title", "label": "Title", "type": "text", "sortable": True},
                    {"key": "url", "label": "URL", "type": "text", "sortable": False},
                    {"key": "category", "label": "Category", "type": "badge", "sortable": True},
                    {"key": "date", "label": "Saved", "type": "date", "sortable": True},
                    {"key": "notes", "label": "Notes", "type": "text", "sortable": False},
                ],
                "default_sort": "date",
                "default_sort_dir": "desc",
                "row_actions": [
                    {
                        "key": "summarize",
                        "label": "Summarize",
                        "icon": "fa-file-lines",
                        "mode": "agent",
                        "prompt_template": "Read and summarize this page: {url}",
                    },
                ],
            },
            {
                "key": "topics",
                "label": "Tracked Topics",
                "icon": "fa-rss",
                "type": "table",
                "source": "research",
                "source_key": "topics",
                "empty_message": "No topics tracked yet. Tell me a subject you're interested in and I'll keep an eye on it!",
                "service_key": "joplin",
                "columns": [
                    {"key": "name", "label": "Topic", "type": "text", "sortable": True},
                    {"key": "category", "label": "Category", "type": "badge", "sortable": True},
                    {
                        "key": "last_checked",
                        "label": "Last Checked",
                        "type": "date",
                        "sortable": True,
                    },
                    {
                        "key": "update_count",
                        "label": "Updates",
                        "type": "number",
                        "sortable": True,
                    },
                    {"key": "latest", "label": "Latest", "type": "text", "sortable": False},
                ],
                "default_sort": "last_checked",
                "default_sort_dir": "desc",
                "row_actions": [
                    {
                        "key": "check_now",
                        "label": "Check Now",
                        "icon": "fa-satellite-dish",
                        "mode": "agent",
                        "prompt_template": (
                            "Check for the latest updates on: {name}."
                            " Search the web and summarize what's new."
                        ),
                    },
                ],
            },
        ],
        "quick_actions": [
            {
                "key": "install_software",
                "label": "Install Software",
                "icon": "fa-download",
                "mode": "agent",
                "prompt": (
                    "What software do you need installed?"
                    " I'll detect your system, find the right package,"
                    " and install it for you."
                ),
            },
            {
                "key": "setup_project",
                "label": "Setup Project",
                "icon": "fa-folder-plus",
                "mode": "agent",
                "prompt": (
                    "I'll create a project directory for you."
                    " What kind of project (Python, Node, Rust, etc.),"
                    " and where should I put it?"
                ),
            },
            {
                "key": "organize_files",
                "label": "Organize Files",
                "icon": "fa-folder-tree",
                "mode": "agent",
                "prompt": (
                    "Which directory needs organizing?"
                    " I'll list what's there, suggest a structure,"
                    " and move things around for you."
                ),
            },
            {
                "key": "system_check",
                "label": "System Check",
                "icon": "fa-stethoscope",
                "mode": "navigate",
                "target": "activity",
            },
            {
                "key": "add_task",
                "label": "Add Task",
                "icon": "fa-plus",
                "mode": "agent",
                "prompt": (
                    "What do you need to get done? I'll create a task with priority and due date."
                ),
            },
            {
                "key": "web_search",
                "label": "Web Search",
                "icon": "fa-magnifying-glass",
                "mode": "navigate",
                "target": "chat",
            },
            {
                "key": "write_config",
                "label": "Write Config",
                "icon": "fa-file-code",
                "mode": "agent",
                "prompt": (
                    "What config file do you need written or edited?"
                    " Give me the path and the values, and I'll write it for you."
                    " (.env, .yaml, .json, .toml, nginx, systemd, etc.)"
                ),
            },
            {
                "key": "compare_products",
                "label": "Compare Products",
                "icon": "fa-scale-balanced",
                "mode": "agent",
                "prompt": (
                    "What are you looking for? I'll research prices,"
                    " reviews, and features across multiple sites."
                ),
            },
            {
                "key": "server_setup",
                "label": "Set Up Server",
                "icon": "fa-server",
                "mode": "navigate",
                "target": "server",
            },
        ],
    },
)

register_job_class(HELPER)
