"""
Configuration Manager
Handles token storage and configuration for the runner
"""
import json
from pathlib import Path
from datetime import datetime
from typing import Optional


class ConfigManager:
    """
    Manages runner configuration and token storage.
    
    Config is stored in ~/.spectra/config.json
    """
    
    CONFIG_DIR = Path.home() / ".spectra"
    CONFIG_FILE = CONFIG_DIR / "config.json"
    DEFAULT_BACKEND_URL = "https://spectra.dev/developer"
    
    def __init__(self):
        """Initialize config manager and ensure directory exists"""
        self.CONFIG_DIR.mkdir(exist_ok=True)
    
    def save_token(self, token: str, backend_url: Optional[str] = None):
        """
        Save authentication token to config file.
        
        Args:
            token: Runner token from Dashboard
            backend_url: Optional custom backend URL
        """
        config = {
            "token": token,
            "backend_url": backend_url or self.DEFAULT_BACKEND_URL,
            "saved_at": datetime.now().isoformat()
        }
        self.CONFIG_FILE.write_text(json.dumps(config, indent=2))
    
    def has_token(self) -> bool:
        """Check if a token is saved"""
        return self.CONFIG_FILE.exists()
    
    def get_token(self) -> str:
        """
        Get the saved token.
        
        Raises:
            ValueError: If no token is saved
        """
        if not self.CONFIG_FILE.exists():
            raise ValueError("No token saved. Run 'spectra-runner login --token YOUR_TOKEN' first.")
        
        config = json.loads(self.CONFIG_FILE.read_text())
        return config["token"]
    
    def get_backend_url(self) -> str:
        """Get the backend URL"""
        if not self.CONFIG_FILE.exists():
            return self.DEFAULT_BACKEND_URL
        
        config = json.loads(self.CONFIG_FILE.read_text())
        return config.get("backend_url", self.DEFAULT_BACKEND_URL)
    
    def get_config(self) -> dict:
        """Get full config"""
        if not self.CONFIG_FILE.exists():
            return {}
        return json.loads(self.CONFIG_FILE.read_text())
    
    def clear(self):
        """Remove saved configuration (logout)"""
        if self.CONFIG_FILE.exists():
            self.CONFIG_FILE.unlink()
