"""Sellable curator approval gate plugin.

Hooks ``post_curator_run`` so newly learned skills under ``skills/learned/`` are
recorded in ``skills/.pending-approvals.json`` and kept disabled in Hermes'
disabled-skills list until a human operator explicitly approves/enables them in
the Sellable Agent Skills panel.
"""

from __future__ import annotations

import json
import logging
import os
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

logger = logging.getLogger("sellable.curator_approval")

PENDING_APPROVALS_FILENAME = ".pending-approvals.json"


def _hermes_home() -> Path:
    try:
        from hermes_constants import get_hermes_home
        return Path(get_hermes_home())
    except Exception:
        return Path(os.getenv("HERMES_HOME") or Path.home() / ".hermes")


def _atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            json.dump(payload, handle, indent=2, sort_keys=True)
            handle.write("\n")
            handle.flush()
            os.fsync(handle.fileno())
        os.chmod(tmp_name, 0o600)
        os.replace(tmp_name, path)
    except Exception:
        try:
            os.unlink(tmp_name)
        except OSError:
            pass
        raise


def _load_approvals(path: Path) -> dict[str, Any]:
    if not path.is_file() or path.is_symlink():
        return {}
    try:
        raw = json.loads(path.read_text(encoding="utf-8"))
        return raw if isinstance(raw, dict) else {}
    except Exception:
        return {}


def reconcile_pending_learned_skills(
    *,
    hermes_home: Path | None = None,
    run_dir: str | None = None,
    dry_run: bool = False,
) -> list[str]:
    """Scan ``skills/learned/*/SKILL.md`` and hold unapproved skills disabled."""
    if dry_run:
        return []
    home = hermes_home or _hermes_home()
    skills_dir = home / "skills"
    learned_dir = skills_dir / "learned"
    if not learned_dir.is_dir():
        return []
    approvals_path = skills_dir / PENDING_APPROVALS_FILENAME
    approvals = _load_approvals(approvals_path)
    newly_pending: list[str] = []
    now_iso = datetime.now(timezone.utc).isoformat()
    changed = False

    for skill_md in sorted(learned_dir.rglob("SKILL.md")):
        if skill_md.is_symlink() or not skill_md.is_file():
            continue
        skill_name = skill_md.parent.name
        if not skill_name:
            continue
        existing = approvals.get(skill_name)
        if isinstance(existing, dict) and existing.get("status") == "approved":
            continue
        if not isinstance(existing, dict) or existing.get("status") != "pending_approval":
            approvals[skill_name] = {
                "status": "pending_approval",
                "recordedAt": now_iso,
                "source": "curator",
                "relativePath": str(skill_md.parent.relative_to(skills_dir)).replace("\\", "/"),
                **({"runDir": str(run_dir)} if run_dir else {}),
            }
            changed = True
            newly_pending.append(skill_name)

    if changed:
        _atomic_write_json(approvals_path, approvals)

    if newly_pending:
        try:
            from hermes_cli.config import load_config
            from hermes_cli.skills_config import get_disabled_skills, save_disabled_skills

            config = load_config()
            disabled = set(get_disabled_skills(config))
            before_count = len(disabled)
            disabled.update(newly_pending)
            if len(disabled) != before_count:
                save_disabled_skills(config, sorted(disabled))
        except Exception as exc:
            logger.warning("[sellable-curator-approval] failed to disable pending learned skills: %s", exc)

    return newly_pending


def _on_post_curator_run(
    run_dir: str | None = None,
    run_json_path: str | None = None,
    report_md_path: str | None = None,
    dry_run: bool = False,
    **kwargs: Any,
) -> None:
    try:
        reconcile_pending_learned_skills(run_dir=run_dir, dry_run=bool(dry_run))
    except Exception as exc:
        logger.debug("[sellable-curator-approval] post_curator_run failed: %s", exc)


def register(ctx) -> None:
    ctx.register_hook("post_curator_run", _on_post_curator_run)
