"""Authentication manager for ReplyMarketing CLI."""

from __future__ import annotations

from datetime import datetime
from typing import Optional

from ..types import Credentials
from ..utils.config import CREDENTIALS_PATH, load_credentials, save_credentials
from ..utils.logger import Logger
from .api_client import ApiClient


class AuthManager:
    """Manages agent authentication and credentials."""

    def __init__(self) -> None:
        self.credentials: Optional[Credentials] = None
        self.api_client = ApiClient()

    def has_valid_credentials(self) -> bool:
        """Check if valid credentials exist and are valid."""
        try:
            Logger.info("Checking for existing credentials")

            # Check if file exists
            if not CREDENTIALS_PATH.exists():
                Logger.info("No credentials file found")
                return False

            # Load credentials
            creds_data = load_credentials()
            if not creds_data:
                return False

            self.credentials = Credentials(
                agent_id=creds_data["agent_id"],
                agent_api_key=creds_data["agent_api_key"],
                agent_name=creds_data["agent_name"],
            )

            Logger.info("Found credentials, verifying with API")

            # Verify with API
            if not self._verify_credentials(self.credentials.agent_api_key):
                Logger.warn("Credentials invalid, deleting file")
                CREDENTIALS_PATH.unlink(missing_ok=True)
                self.credentials = None
                return False

            Logger.info("Credentials are valid")
            return True

        except Exception as e:
            Logger.info(f"No valid credentials found: {e}")
            return False

    def _verify_credentials(self, api_key: str) -> bool:
        """Verify credentials with API."""
        try:
            client = ApiClient(api_key)
            response = client.get("/agents/me")
            return response.success
        except Exception:
            return False

    def register_agent(self, agent_name: str, metadata: Optional[dict] = None) -> Credentials:
        """Register a new agent."""
        Logger.info("Registering new agent", {"agent_name": agent_name, "metadata": metadata})

        response = self.api_client.post(
            "/agents/register",
            {
                "agentName": agent_name,
                "metadata": metadata
                or {"purpose": "content-marketing", "setup_date": datetime.now().isoformat()},
            },
        )

        if not response.success or not response.data:
            raise Exception(response.error or "Registration failed")

        data = response.data
        credentials = Credentials(
            agent_id=data["agentId"], agent_api_key=data["agentApiKey"], agent_name=agent_name
        )

        # Save credentials
        self._save_credentials(credentials)
        self.credentials = credentials

        Logger.info("Agent registered successfully", {"agent_id": credentials.agent_id})

        return credentials

    def _save_credentials(self, credentials: Credentials) -> None:
        """Save credentials to file."""
        save_credentials(
            {
                "agent_id": credentials.agent_id,
                "agent_api_key": credentials.agent_api_key,
                "agent_name": credentials.agent_name,
            }
        )

    def get_credentials(self) -> Optional[Credentials]:
        """Get current credentials."""
        return self.credentials

    def get_api_key(self) -> Optional[str]:
        """Get API key from credentials."""
        return self.credentials.agent_api_key if self.credentials else None

    def get_agent_id(self) -> Optional[str]:
        """Get agent ID from credentials."""
        return self.credentials.agent_id if self.credentials else None

    def get_agent_name(self) -> Optional[str]:
        """Get agent name from credentials."""
        return self.credentials.agent_name if self.credentials else None

    def reload_from_disk(self) -> None:
        """Reload credentials from disk."""
        self.has_valid_credentials()
