import logging
from pathlib import Path
from core.config import config

logger = logging.getLogger("core.conductor.identity")

# Mapping from tier name to agent definition file
TIER_AGENTS = {
    "BASIC": "l1-basic.md",
    "STANDARD": "l2-digital-employee.md",
    "PRO": "l3-domain-expert.md",
    "ENTERPRISE": "l4-executive.md",
}


class Identity:
    """
    Manages the Agent Persona and Rules.
    Source of Truth: .agent/rules/project-goals.md + tier agent definition.
    """
    def __init__(self, tier: str = "ENTERPRISE"):
        self.persona_name = "Antigravity"
        self.tier = tier.upper()
        self.rules_content = ""
        self.agent_definition = ""

    def load(self) -> bool:
        """
        Load immutable project rules and tier-specific agent definition.
        """
        # 1. Load project rules
        rules_path = config.RULES_DIR / "project-goals.md"
        if not rules_path.exists():
            logger.error(f"FATAL: Identity Rules missing at {rules_path}")
            return False

        try:
            self.rules_content = rules_path.read_text(encoding='utf-8')
            logger.info(f"Identity Loaded: {self.persona_name}")
        except Exception as e:
            logger.error(f"Failed to load Identity: {e}")
            return False

        # 2. Load tier-specific agent definition
        agent_file = TIER_AGENTS.get(self.tier)
        if agent_file:
            agents_dir = config.ROOT_DIR / ".claude" / "agents"
            agent_path = agents_dir / agent_file
            if agent_path.exists():
                try:
                    self.agent_definition = agent_path.read_text(encoding='utf-8')
                    logger.info(f"Agent definition loaded: {agent_file} (tier={self.tier})")
                except Exception as e:
                    logger.warning(f"Failed to load agent definition {agent_file}: {e}")
            else:
                logger.warning(f"Agent definition not found: {agent_path}")
        else:
            logger.warning(f"No agent definition mapped for tier: {self.tier}")

        return True

    def get_system_instruction(self) -> str:
        """
        Returns the compiled system prompt including tier agent definition.
        """
        parts = [
            f"IDENTITY: {self.persona_name}",
            f"TIER: {self.tier}",
            "",
            "MANDATE:",
            self.rules_content,
        ]

        if self.agent_definition:
            parts.extend([
                "",
                "AGENT DEFINITION:",
                self.agent_definition,
            ])

        return "\n".join(parts)
