#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Adapter for external domains: Brain and Agents."""
from __future__ import annotations

import logging

try:
    from pulse.brain.pulse_boot import boot as pulse_boot_run
except Exception:
    pulse_boot_run = None

try:
    from pulse.brain.pulse_save import save as pulse_save_run
except Exception:
    pulse_save_run = None


def load_domain_skills(domain: str, skills_used: bool) -> tuple[str, list[str]]:
    """Loads domain skills via the Agents module safely."""
    try:
        from pulse.agents.pulse_wrapper import load_skills_for_domain
        return load_skills_for_domain(domain, max_skills=2, skills_used=skills_used)
    except Exception:
        return "", []


def build_system_context(worker_id: str, tier: str, title: str, domain: str) -> str:
    """Builds the initial system context via pulse_boot."""
    if pulse_boot_run:
        try:
            return pulse_boot_run(worker_id, tier, do_claim=False, task_query=f"{title} {domain}")
        except Exception:
            pass
    return f"You are {worker_id}, a PULSE worker (tier: {tier}).\n"


def save_learnings(log: logging.Logger, worker_id: str, task_id: str, outcome: str, domain: str, trace: list[dict], failures: list[str], loaded_skills: list[str]):
    """Abstracts the pulse_save call to avoid importing brain in execution."""
    if pulse_save_run:
        try:
            hi = [e["content"] for e in trace if e["salience"] >= 2.0 and e["type"] != "error"]
            er = [e["content"] for e in trace if e["type"] == "error"]
            pulse_save_run(
                agent_name=worker_id, task_id=task_id, outcome=outcome, domain=domain,
                learnings=hi[:5] or ([outcome] if outcome else []), failures=er + failures, skills_used=loaded_skills
            )
        except Exception as e:
            log.warning("pulse_save failed: %s", e)
