# 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

"""
Digital Broker job class — cost transparency, provider optimization,
and economic intelligence for the agent's own operations.
"""

from . import JobClass, register_job_class

DIGITAL_BROKER = JobClass(
    key="digital_broker",
    name="Digital Broker",
    icon="fa-chart-line",
    description="Cost tracking, provider optimization, and economic intelligence",
    prompt_fragment="""You are operating in Digital Broker mode — the economic intelligence layer.

Your core mission is radical cost transparency: every LLM call, every token, every cent
should be visible, explainable, and optimizable. You treat the user's AI budget the way
a good financial advisor treats a client's portfolio.

**Primary responsibilities:**

1. **Cost Awareness** — Always know current spend: today, this month, projected.
   When asked about cost, pull real numbers from analytics, never estimate.
   Surface cost implications proactively when the user is about to do something expensive.

2. **Provider Optimization** — Monitor which models deliver best value for each task type.
   Track cost-per-task by skill. Recommend routing changes when a cheaper model performs
   equally well. Know the price of every provider cold.

3. **Budget Management** — Help set and enforce budgets. Alert before thresholds are hit,
   not after. Suggest proactive cost reductions (disable expensive scheduled tasks,
   switch to lighter models for simple queries, batch operations).

4. **Proactive vs Interactive Analysis** — Track what the agent does autonomously
   (briefings, heartbeats, inbox monitors) vs what the user directly requests.
   Surface this split clearly — the user should never be surprised by background spend.

5. **Dross Economics** — When mesh sharing is active, track borrowed-use costs,
   usage records, and token balances. Help the user understand the value exchange
   happening across the mesh network.

6. **Training ROI** — Monitor the cost of generating training-eligible memories
   vs the value they provide (reuse count, sharing frequency). Help ensure the
   co-op learning pipeline is cost-effective.

**Decision framework:**
- Default to the cheapest model that can handle the task
- Escalate to expensive models only when complexity demands it
- Treat every proactive/scheduled task as a recurring cost commitment
- Surface unit economics: cost per email triaged, cost per briefing, cost per search
- Never hide costs behind aggregates — drill down to the individual call

**Communication style:**
- Lead with numbers, not narratives
- Use tables and comparisons over paragraphs
- When recommending changes, always show the math: "Switching briefings from
  Claude to Gemini saves $X.XX/month (Y calls × $Z.ZZ difference per call)"
- Be direct about waste: if something costs more than its value, say so""",
    skill_weights={
        # Analytics & cost tools
        "daily_briefing": 0.8,
        "proactive_status": 0.9,
        "set_briefing_time": 0.8,
        "set_deadline_alerts": 0.7,
        "check_deadlines": 0.7,
        "heartbeat_check": 0.7,
        # Research & notes for tracking
        "web_search": 0.6,
        "write_note": 0.8,
        "search_notes": 0.8,
        "remember": 0.9,
        "recall": 0.9,
        # Task management for budget actions
        "create_task": 0.7,
        "complete_task": 0.6,
        "list_tasks": 0.7,
        # Mesh & Dross economics
        "mesh_status": 0.8,
        "dross_balance": 0.9,
        "dross_history": 0.8,
        # Round table for cross-job analysis
        "query_chairman": 0.7,
        "smart_intake": 0.5,
        "review_intake": 0.4,
    },
    species_flavor={
        "fox": "Your fox brings sharp-eyed deal instincts — spotting savings others miss, "
        "negotiating the best value from every provider.",
        "owl": "Your owl brings methodical ledger precision — every token accounted for, "
        "every trend spotted before it becomes a problem.",
        "cat": "Your cat brings elegant efficiency — minimum spend, maximum effect, "
        "finding the laziest path to the same result.",
        "dragon": "Your dragon brings commanding oversight — enforcing budgets with authority, "
        "burning through waste without hesitation.",
        "wolf": "Your wolf brings pack economics — tracking shared costs across the mesh, "
        "ensuring every node pulls its weight.",
        "frog": "Your frog brings adaptive budgeting — adjusting spend in real-time "
        "as priorities shift, never locked into yesterday's plan.",
    },
    recommended_connects=[
        "email",
    ],
    proactive_focus=[
        "daily cost summary compared to budget and last month",
        "alert when proactive tasks exceed 30% of total spend",
        "weekly provider efficiency report — cost per successful call by model",
        "flag skills or tools with poor cost-to-value ratio",
        "monthly mesh economics review — Dross earned vs spent",
    ],
    workspace={
        "label": "Cost Center",
        "icon": "fa-chart-line",
        "description": "Full visibility into your AI spend — every call, every token, every cent.",
        "overview": {
            "cards": [
                {
                    "key": "today_cost",
                    "label": "Today's Cost",
                    "icon": "fa-dollar-sign",
                    "color": "#60a5fa",
                    "source": "analytics",
                    "metric": "today_cost",
                    "format": "currency",
                },
                {
                    "key": "month_cost",
                    "label": "This Month",
                    "icon": "fa-calendar",
                    "color": "#34d399",
                    "source": "analytics",
                    "metric": "month_cost",
                    "format": "currency",
                },
                {
                    "key": "projected_cost",
                    "label": "Projected",
                    "icon": "fa-chart-line",
                    "color": "#fbbf24",
                    "source": "analytics",
                    "metric": "projected_cost",
                    "format": "currency",
                },
                {
                    "key": "today_calls",
                    "label": "Today's Calls",
                    "icon": "fa-phone",
                    "color": "#a78bfa",
                    "source": "analytics",
                    "metric": "today_calls",
                    "format": "number",
                },
                {
                    "key": "month_tokens",
                    "label": "Month Tokens",
                    "icon": "fa-microchip",
                    "color": "#f87171",
                    "source": "analytics",
                    "metric": "month_tokens",
                    "format": "number",
                },
                {
                    "key": "proactive_pct",
                    "label": "Proactive %",
                    "icon": "fa-robot",
                    "color": "#c084fc",
                    "source": "analytics",
                    "metric": "proactive_pct",
                    "format": "percent",
                },
            ],
        },
        "sections": [
            {
                "key": "call_log",
                "label": "Recent Calls",
                "icon": "fa-list",
                "type": "table",
                "source": "analytics",
                "source_key": "calls",
                "empty_message": "No LLM calls recorded yet.",
                "columns": [
                    {"key": "timestamp", "label": "Time", "type": "date", "sortable": True},
                    {"key": "trigger", "label": "Trigger", "type": "badge"},
                    {"key": "model", "label": "Model", "type": "text"},
                    {"key": "tokens_in", "label": "In", "type": "number"},
                    {"key": "tokens_out", "label": "Out", "type": "number"},
                    {"key": "cost_usd", "label": "Cost", "type": "currency", "sortable": True},
                    {"key": "latency_ms", "label": "Latency", "type": "number"},
                ],
                "default_sort": "timestamp",
                "default_sort_dir": "desc",
            },
            {
                "key": "spend_breakdown",
                "label": "Spend Breakdown",
                "icon": "fa-chart-pie",
                "type": "summary",
                "source": "analytics",
                "stats": [
                    {
                        "key": "interactive_cost",
                        "label": "Interactive",
                        "icon": "fa-user",
                        "color": "#60a5fa",
                        "metric": "interactive_cost",
                        "format": "currency",
                    },
                    {
                        "key": "proactive_cost",
                        "label": "Proactive",
                        "icon": "fa-robot",
                        "color": "#a78bfa",
                        "metric": "proactive_cost",
                        "format": "currency",
                    },
                    {
                        "key": "daily_avg",
                        "label": "Daily Average",
                        "icon": "fa-chart-bar",
                        "color": "#34d399",
                        "metric": "daily_avg",
                        "format": "currency",
                    },
                    {
                        "key": "last_month",
                        "label": "Last Month",
                        "icon": "fa-history",
                        "color": "#fbbf24",
                        "metric": "last_month_total",
                        "format": "currency",
                    },
                ],
            },
            {
                "key": "skill_costs",
                "label": "Cost by Skill",
                "icon": "fa-tags",
                "type": "table",
                "source": "analytics",
                "source_key": "skill_costs",
                "empty_message": "No skill cost data yet.",
                "columns": [
                    {"key": "skill", "label": "Skill", "type": "text", "sortable": True},
                    {"key": "calls", "label": "Calls", "type": "number", "sortable": True},
                    {"key": "cost", "label": "Cost", "type": "currency", "sortable": True},
                    {"key": "avg_latency", "label": "Avg Latency", "type": "number"},
                ],
                "default_sort": "cost",
                "default_sort_dir": "desc",
            },
        ],
        "quick_actions": [
            {
                "key": "cost_report",
                "label": "Cost Report",
                "icon": "fa-file-invoice-dollar",
                "mode": "agent",
                "prompt": "Give me a detailed cost report: today's spend, this month's total, "
                "projected end-of-month, breakdown by proactive vs interactive, "
                "top spending skills, and any optimization recommendations.",
            },
            {
                "key": "optimize",
                "label": "Optimize Spend",
                "icon": "fa-wand-magic-sparkles",
                "mode": "agent",
                "prompt": "Analyze my current LLM usage and recommend specific optimizations: "
                "Which scheduled tasks could use a cheaper model? What's the proactive "
                "spend ratio? Are there any skills with poor cost-to-value ratios?",
            },
            {
                "key": "budget_check",
                "label": "Budget Status",
                "icon": "fa-gauge",
                "mode": "agent",
                "prompt": "Check my current budget status: monthly spend vs any set limits, "
                "projected overage risk, and how today compares to my daily average.",
            },
            {
                "key": "provider_compare",
                "label": "Compare Providers",
                "icon": "fa-scale-balanced",
                "mode": "agent",
                "prompt": "Compare my available LLM providers by cost-effectiveness: "
                "show cost per 1K tokens for each, success rates, average latency, "
                "and recommend the best default for my usage pattern.",
            },
        ],
    },
)

register_job_class(DIGITAL_BROKER)
