"""Agent identity management for the ALP network.

Each Alive instance has a persistent identity stored at ~/.alive/identity.json.
The identity is generated on first run and includes a unique agent ID, optional
alias, and protocol version info.
"""

from __future__ import annotations

import json
import time
import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Any


_start_time = time.monotonic()


def _identity_path() -> Path:
    from alive.config import ALIVE_HOME

    return ALIVE_HOME / "identity.json"


def get_or_create_identity() -> dict[str, Any]:
    """Load existing identity or create a new one.

    Returns:
        Identity dict with agent_id, alias, created_at, alp_version,
        alive_version.
    """
    path = _identity_path()
    if path.exists():
        return json.loads(path.read_text())

    from alive import __version__

    identity: dict[str, Any] = {
        "agent_id": f"alp-{uuid.uuid4()}",
        "alias": None,
        "created_at": datetime.now(timezone.utc).isoformat(),
        "alp_version": "0.1.0",
        "alive_version": __version__,
    }
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(identity, indent=2))
    return identity


def get_agent_card() -> dict[str, Any]:
    """Build a live agent card with identity + current skill data.

    Returns:
        Dict with agent_id, alias, skills list, skill_count,
        integrations list, alp_version, and uptime_seconds.
    """
    identity = get_or_create_identity()

    from alive.core.skill_registry import get_registry

    registry = get_registry()
    skills_raw = registry.list_skills_only()
    skills = []
    for s in skills_raw:
        meta_path = registry._skills_dir / s.name / "metadata.json"
        generation = 1
        if meta_path.exists():
            try:
                meta = json.loads(meta_path.read_text())
                generation = meta.get("generation", 1)
            except (json.JSONDecodeError, OSError):
                pass
        skills.append(
            {
                "name": s.name,
                "description": s.description,
                "confidence": s.confidence_score,
                "generation": generation,
            }
        )

    from alive.integrations import get_available_integrations

    integrations = [
        name
        for name, info in get_available_integrations().items()
        if info.get("configured")
    ]

    return {
        "agent_id": identity["agent_id"],
        "alias": identity.get("alias"),
        "skills": skills,
        "skill_count": len(skills),
        "integrations": integrations,
        "alp_version": identity.get("alp_version", "0.1.0"),
        "uptime_seconds": int(time.monotonic() - _start_time),
    }


def set_alias(alias: str) -> None:
    """Update the alias in identity.json.

    Args:
        alias: Human-readable name for this agent.
    """
    identity = get_or_create_identity()
    identity["alias"] = alias
    _identity_path().write_text(json.dumps(identity, indent=2))
