"""
enterprise/skill_marketplace.py — Enterprise skill marketplace.

Department-level skill sharing with permission control.
"""

from __future__ import annotations

import hashlib
import logging
import time
from dataclasses import dataclass, field
from typing import Any

logger = logging.getLogger(__name__)


@dataclass
class SkillStep:
    """A single step in a skill."""
    order: int
    description: str
    expected_outcome: str = ""
    tips: str = ""


@dataclass
class SkillPackage:
    """A portable, shareable skill package."""
    skill_id: str = ""
    name: str = ""
    description: str = ""
    category: str = ""
    source_agent: str = ""
    created_at: float = 0.0
    updated_at: float = 0.0
    usage_count: int = 0
    rating: float = 0.0
    steps: list[SkillStep] = field(default_factory=list)
    examples: list[str] = field(default_factory=list)
    prerequisites: list[str] = field(default_factory=list)
    visibility: str = "team"
    tags: list[str] = field(default_factory=list)

    def __post_init__(self):
        if not self.skill_id:
            self.skill_id = self._generate_id()
        if not self.created_at:
            self.created_at = time.time()

    def _generate_id(self) -> str:
        raw = f"{self.name}:{self.category}:{self.source_agent}"
        return f"skill_{hashlib.sha256(raw.encode()).hexdigest()[:12]}"

    def to_dict(self) -> dict[str, Any]:
        return {
            "skill_id": self.skill_id,
            "name": self.name,
            "description": self.description,
            "category": self.category,
            "source_agent": self.source_agent,
            "created_at": self.created_at,
            "updated_at": self.updated_at,
            "usage_count": self.usage_count,
            "rating": self.rating,
            "steps": [
                {"order": s.order, "description": s.description,
                 "expected_outcome": s.expected_outcome, "tips": s.tips}
                for s in self.steps
            ],
            "examples": self.examples,
            "prerequisites": self.prerequisites,
            "visibility": self.visibility,
            "tags": self.tags,
        }

    @classmethod
    def from_dict(cls, data: dict) -> SkillPackage:
        steps = [SkillStep(**s) for s in data.get("steps", [])]
        return cls(
            skill_id=data.get("skill_id", ""),
            name=data.get("name", ""),
            description=data.get("description", ""),
            category=data.get("category", ""),
            source_agent=data.get("source_agent", ""),
            created_at=data.get("created_at", 0),
            updated_at=data.get("updated_at", 0),
            usage_count=data.get("usage_count", 0),
            rating=data.get("rating", 0.0),
            steps=steps,
            examples=data.get("examples", []),
            prerequisites=data.get("prerequisites", []),
            visibility=data.get("visibility", "team"),
            tags=data.get("tags", []),
        )


class SkillMarketplace:
    """Enterprise skill marketplace for department-level sharing.

    Extends SkillDistributor with department-based visibility
    and the enterprise permission matrix.
    """

    def __init__(self, store=None, skill_distributor=None,
                 permission_matrix=None):
        self.store = store
        self.skill_distributor = skill_distributor
        self.permission_matrix = permission_matrix

    def publish(self, skill: SkillPackage, department: str = "") -> str:
        """Publish a skill to the department marketplace."""
        skill.visibility = "team"
        if self.skill_distributor:
            return self.skill_distributor.share_skill(
                skill, from_agent=skill.source_agent, visibility="team"
            )
        return skill.skill_id

    def browse(self, category: str = "", agent_id: str = "",
               department: str = "") -> list[SkillPackage]:
        """Browse available skills in the marketplace.

        Filtered by the agent's permission level.
        """
        if self.skill_distributor:
            vis_filter = ["public", "team"]
            if self.permission_matrix:
                # Check if agent has access to internal skills
                has_internal = self.permission_matrix.check_access(
                    "member", department, "internal", "read"
                )
                if has_internal:
                    vis_filter.append("internal")
            return self.skill_distributor.request_skill(
                category=category, agent_id=agent_id,
                visibility_filter=vis_filter,
            )
        return []

    def recommend(self, agent_id: str, limit: int = 5) -> list[SkillPackage]:
        """Recommend skills based on agent's work patterns.

        Simple heuristic: recommend most-used skills in categories
        the agent hasn't used yet.
        """
        if not self.skill_distributor:
            return []

        # Get all categories
        all_skills = self.skill_distributor.request_skill(
            category="", agent_id=agent_id,
        )
        if not all_skills:
            return []

        # Sort by rating and usage
        scored = sorted(all_skills,
                       key=lambda s: (s.rating * 0.6 + min(s.usage_count / 50, 1.0) * 0.4),
                       reverse=True)
        return scored[:limit]
