"""Configuration management for RunSentry agent."""

import os
import sys
import yaml
from pathlib import Path
from typing import Optional, Dict, Any


CONFIG_PATH = Path("/etc/runsentry/config.yaml")
CONFIG_DIR = CONFIG_PATH.parent


class Config:
    """Agent configuration."""

    def __init__(self):
        self.agent_id: Optional[str] = None
        self.backend_url: str = "https://runsentry-api.azurewebsites.net/"
        self.token: Optional[str] = None  # Non-expiring token from registration
        self.agent_name: Optional[str] = None
        self.workspace_id: Optional[str] = None
        self.discovery_interval: int = 3600  # 1 hour in seconds
        self.heartbeat_interval: int = 300  # 5 minutes in seconds
        self.flush_interval: int = 60  # 1 minute in seconds
        self._loaded = False

    def load(self) -> bool:
        """Load configuration from file."""
        if not CONFIG_PATH.exists():
            return False

        try:
            with open(CONFIG_PATH, "r") as f:
                data = yaml.safe_load(f) or {}
                self.agent_id = data.get("agent_id")
                self.backend_url = data.get("backend_url", self.backend_url)
                self.token = data.get("token")
                self.agent_name = data.get("agent_name")
                self.workspace_id = data.get("workspace_id")
                self.discovery_interval = data.get("discovery_interval", self.discovery_interval)
                self.heartbeat_interval = data.get("heartbeat_interval", self.heartbeat_interval)
                self.flush_interval = data.get("flush_interval", self.flush_interval)
                self._loaded = True
                return True
        except Exception as e:
            # Use print here since logging may not be initialized yet
            print(f"Warning: Failed to load config: {e}", file=sys.stderr)
            return False

    def save(self):
        """Save configuration to file."""
        CONFIG_DIR.mkdir(parents=True, exist_ok=True)

        data = {
            "agent_id": self.agent_id,
            "backend_url": self.backend_url,
            "token": self.token,
            "agent_name": self.agent_name,
            "workspace_id": self.workspace_id,
            "discovery_interval": self.discovery_interval,
            "heartbeat_interval": self.heartbeat_interval,
            "flush_interval": self.flush_interval,
        }

        with open(CONFIG_PATH, "w") as f:
            yaml.dump(data, f)

        # Set secure permissions
        os.chmod(CONFIG_PATH, 0o600)

    def is_configured(self) -> bool:
        """Check if agent is properly configured."""
        return bool(self.agent_id and self.token and self.backend_url)


# Global config instance
_config = Config()


def get_config() -> Config:
    """Get global configuration instance."""
    if not _config._loaded:
        _config.load()
    return _config

