# 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

"""
Job Class System — Final Fantasy-inspired agent roles.

Adds a 4th axis to the Personality Triangle: *what role* the agent fills.
Users can switch class anytime via the dashboard, like switching jobs in FFV.

Initial classes:
  - Helper      — general-purpose assistant (default, no extra prompt)
  - Social Worker — case management, advocacy, resource navigation
  - Business Buddy — productivity, scheduling, professional comms
"""

from __future__ import annotations

import json
import logging
from dataclasses import dataclass, field
from typing import Optional

from ..core.paths import DATA_DIR

logger = logging.getLogger(__name__)

JOB_CLASS_REGISTRY: dict[str, "JobClass"] = {}


@dataclass
class JobClass:
    """Definition of an agent job class (role specialization)."""

    key: str  # "social_worker", "helper", "business_buddy"
    name: str  # "Social Worker"
    icon: str  # Font Awesome icon name
    description: str  # One-line summary
    prompt_fragment: str  # Injected into system prompt after species voice
    skill_weights: dict[str, float] = field(default_factory=dict)  # tool -> priority boost
    species_flavor: dict[str, str] = field(default_factory=dict)  # species_key -> flavor text
    recommended_connects: list[str] = field(default_factory=list)  # Service keys to suggest
    proactive_focus: list[str] = field(default_factory=list)  # Topics for proactive check-ins
    workspace: dict = field(default_factory=dict)  # Dashboard workspace config


def register_job_class(cls: JobClass) -> None:
    """Register a job class in the global registry."""
    JOB_CLASS_REGISTRY[cls.key] = cls
    logger.debug("Registered job class: %s", cls.key)


def get_job_class(key: str) -> Optional[JobClass]:
    """Look up a job class by key. Returns None if not found."""
    return JOB_CLASS_REGISTRY.get(key)


def list_job_classes() -> list[JobClass]:
    """Return all registered job classes, sorted by key."""
    return sorted(JOB_CLASS_REGISTRY.values(), key=lambda jc: jc.key)


def get_active_job_class() -> Optional[JobClass]:
    """Read from creature state, return the active JobClass or None."""
    try:
        from ..creature.state import load_creature

        creature = load_creature()
        if creature and creature.job_class:
            return JOB_CLASS_REGISTRY.get(creature.job_class)
    except Exception as e:
        logger.debug("Error suppressed: %s", e)
    return None


def _load_custom_job_classes():
    """Load job classes from JSON files in custom_job_classes directory."""
    custom_dir = DATA_DIR / "custom_job_classes"
    if not custom_dir.exists():
        return
    for f in custom_dir.glob("*.json"):
        try:
            data = json.loads(f.read_text())
            jc_data = data.get("job_class", data)
            jc = JobClass(
                **{k: v for k, v in jc_data.items() if k in JobClass.__dataclass_fields__}
            )
            register_job_class(jc)
        except Exception as e:
            logger.warning("Failed to load custom job class from %s: %s", f, e)


# Auto-import job class modules to populate the registry
from . import artist as _ar  # noqa: E402, F401
from . import business_buddy as _bb  # noqa: E402, F401
from . import chef as _ch  # noqa: E402, F401
from . import helper as _h  # noqa: E402, F401
from . import nonprofit_director as _np  # noqa: E402, F401
from . import social_worker as _sw  # noqa: E402, F401

# Load custom job classes after built-in ones
_load_custom_job_classes()
