#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
Config Manager: DEPRECATED — use brain_utils.py instead.

All path constants and env var overrides (PULSE_ROOT, PULSE_BRAIN_DIR,
PULSE_STATE_DIR, PULSE_TASK_BOARD) are now in brain_utils.py.

    from pulse.core.brain_utils import ROOT_DIR, HIPPOCAMPUS_DIR, STATE_DIR, TASK_BOARD_FILE

This file is kept for backward compatibility only. No files import it.

Dependencies: Python stdlib only (Law 4)
"""

import os
from pathlib import Path


def _resolve_root() -> Path:
    """Find PULSE root directory by walking up from this file."""
    current = Path(__file__).resolve().parent
    # Walk up to find PULSE_OS.md or .git
    for _ in range(5):
        if (current / "PULSE_OS.md").exists() or (current / ".git").exists():
            return current
        current = current.parent
    # Fallback: assume standard layout
    return Path(__file__).resolve().parent.parent.parent


class Config:
    """Centralized PULSE configuration with environment overrides."""

    def __init__(self, root: Path = None):
        self._root = root or _resolve_root()

    @property
    def root(self) -> Path:
        return Path(os.environ.get("PULSE_ROOT", str(self._root)))

    # --- Brain paths ---
    @property
    def brain_dir(self) -> Path:
        return Path(os.environ.get("PULSE_BRAIN_DIR",
                    str(self.root / "Hippocampus")))

    @property
    def lessons_dir(self) -> Path:
        return self.brain_dir / "Lessons"

    @property
    def failures_dir(self) -> Path:
        return self.brain_dir / "Failures"

    @property
    def patterns_dir(self) -> Path:
        return self.brain_dir / "Patterns"

    @property
    def evidence_dir(self) -> Path:
        return self.brain_dir / "Evidence"

    @property
    def knowledge_dir(self) -> Path:
        return self.brain_dir / "Knowledge"

    @property
    def private_dir(self) -> Path:
        return self.brain_dir / "Private"

    # --- System paths ---
    @property
    def state_dir(self) -> Path:
        return Path(os.environ.get("PULSE_STATE_DIR",
                    str(self.root / "state")))

    @property
    def tools_dir(self) -> Path:
        return self.root / "pulse" / "brain"

    @property
    def daemons_dir(self) -> Path:
        return self.root / "pulse" / "daemons"

    @property
    def skills_dir(self) -> Path:
        return self.root / ".cursor" / "skills"

    # --- Key files ---
    @property
    def task_board(self) -> Path:
        return Path(os.environ.get("PULSE_TASK_BOARD",
                    str(self.root / "Prefrontal_Cortex" / "Action_Queue" / "task_board.json")))

    @property
    def agent_registry(self) -> Path:
        return self.state_dir / "agent_registry.json"

    @property
    def constitution(self) -> Path:
        return self.root / "Corpus_Callosum" / "CONSTITUTION.md"

    @property
    def laws(self) -> Path:
        return self.root / "Corpus_Callosum" / "CONSTITUTION.md"

    @property
    def anti_patterns_dir(self) -> Path:
        return self.root / "Hippocampus" / "Patterns"

    @property
    def brain_config(self) -> Path:
        return self.brain_dir / "brain_config.json"

    @property
    def growth_metrics(self) -> Path:
        return self.state_dir / "growth_metrics.json"

    # --- Runtime settings ---
    @property
    def log_level(self) -> str:
        return os.environ.get("PULSE_LOG_LEVEL", "INFO")

    @property
    def max_brain_results(self) -> int:
        return int(os.environ.get("PULSE_MAX_BRAIN_RESULTS", "10"))

    @property
    def dedup_interval(self) -> int:
        """Dedup interval in seconds."""
        return int(os.environ.get("PULSE_DEDUP_INTERVAL", str(6 * 3600)))

    def ensure_dirs(self) -> None:
        """Create all required directories if they don't exist."""
        for d in [self.brain_dir, self.lessons_dir, self.failures_dir,
                  self.patterns_dir, self.evidence_dir, self.knowledge_dir,
                  self.private_dir, self.state_dir]:
            d.mkdir(parents=True, exist_ok=True)

    def to_dict(self) -> dict:
        """Export all config as dictionary (useful for debugging)."""
        return {
            "root": str(self.root),
            "brain_dir": str(self.brain_dir),
            "state_dir": str(self.state_dir),
            "tools_dir": str(self.tools_dir),
            "task_board": str(self.task_board),
            "log_level": self.log_level,
        }


# Singleton instance for convenience
_config = None


def get_config() -> Config:
    """Get or create singleton Config instance."""
    global _config
    if _config is None:
        _config = Config()
    return _config


if __name__ == "__main__":
    import json
    config = Config()
    print(json.dumps(config.to_dict(), indent=2))
