"""Serialization helpers for structured skill lifecycle objects."""

from __future__ import annotations

from hashlib import sha256
import json
from typing import Any


def json_dumps(payload: Any) -> str:
    return json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True)


def canonical_hash(text: str) -> str:
    return sha256(text.encode("utf-8")).hexdigest()


def normalize_frontmatter(frontmatter: dict[str, Any] | None) -> dict[str, Any]:
    raw = dict(frontmatter or {})
    normalized: dict[str, Any] = {}
    for key, value in raw.items():
        if value is None:
            continue
        if isinstance(value, str):
            cleaned = value.strip()
            if cleaned:
                normalized[str(key)] = cleaned
            continue
        if isinstance(value, list):
            items = [str(item).strip() for item in value if str(item).strip()]
            normalized[str(key)] = items
            continue
        normalized[str(key)] = value
    return normalized


def summarize_skill_content(content: str, *, max_lines: int = 3, max_chars: int = 240) -> str:
    lines = [line.strip() for line in content.splitlines() if line.strip()]
    if not lines:
        return ""
    summary = " ".join(lines[:max_lines]).strip()
    return summary[:max_chars].strip()
