"""
Authentication status checking.

Checks if user is logged in to various services.
Does NOT handle credentials - just checks status.
"""

import subprocess
import os
from dataclasses import dataclass
from typing import Optional

from .config import Config


@dataclass
class AuthStatus:
    """Authentication status for all services."""
    teleport_logged_in: bool = False
    teleport_user: Optional[str] = None
    teleport_expires: Optional[str] = None

    apollo_configured: bool = False

    docker_logged_in: bool = False
    docker_registry: Optional[str] = None

    aws_configured: bool = False
    aws_identity: Optional[str] = None

    @property
    def all_ready(self) -> bool:
        """Check if all required auth is in place."""
        return (
            self.teleport_logged_in and
            self.apollo_configured and
            self.aws_configured
        )


class AuthManager:
    """
    Manages authentication status checks.

    This class only CHECKS status - it does not store or handle credentials.
    Actual login is done by running native CLI commands.
    """

    def __init__(self, config: Config):
        self.config = config

    def check_all(self) -> AuthStatus:
        """Check authentication status for all services."""
        status = AuthStatus()

        # Check Teleport
        tsh_status = self._check_teleport()
        status.teleport_logged_in = tsh_status.get("logged_in", False)
        status.teleport_user = tsh_status.get("user")
        status.teleport_expires = tsh_status.get("expires")

        # Check Apollo CLI
        status.apollo_configured = self._check_apollo()

        # Check Docker
        docker_status = self._check_docker()
        status.docker_logged_in = docker_status.get("logged_in", False)
        status.docker_registry = docker_status.get("registry")

        # Check AWS
        aws_status = self._check_aws()
        status.aws_configured = aws_status.get("configured", False)
        status.aws_identity = aws_status.get("identity")

        return status

    def _check_teleport(self) -> dict:
        """Check Teleport login status."""
        try:
            result = subprocess.run(
                ["tsh", "status", "--format=json"],
                capture_output=True,
                text=True,
                timeout=10
            )

            if result.returncode == 0:
                import json
                data = json.loads(result.stdout)
                active = data.get("active", {})

                # Check if session is valid (not expired)
                if active.get("username"):
                    return {
                        "logged_in": True,
                        "user": active.get("username"),
                        "cluster": active.get("cluster"),
                        "expires": active.get("valid_until"),
                    }

            return {"logged_in": False}

        except subprocess.TimeoutExpired:
            return {"logged_in": False, "error": "timeout"}
        except FileNotFoundError:
            return {"logged_in": False, "error": "tsh not found"}
        except Exception as e:
            return {"logged_in": False, "error": str(e)}

    def _check_apollo(self) -> bool:
        """Check if Apollo CLI is configured."""
        try:
            # Apollo CLI doesn't have a simple "am I configured" check
            # We check if the command exists and doesn't error
            result = subprocess.run(
                ["which", "apollo-cli"],
                capture_output=True,
                timeout=5
            )

            if result.returncode != 0:
                return False

            # Check if APOLLO_CLIENT env var is set (one way to configure)
            if os.environ.get("APOLLO_CLIENT") and os.environ.get("APOLLO_SECRET"):
                return True

            # Could also check for config file, but env vars are the main method
            return self.config.apollo.configured

        except Exception:
            return False

    def _check_docker(self) -> dict:
        """Check Docker login status for the registry."""
        try:
            import json
            docker_config = Path.home() / ".docker" / "config.json"

            if docker_config.exists():
                data = json.loads(docker_config.read_text())
                auths = data.get("auths", {})

                registry = self.config.docker.registry
                if registry in auths:
                    return {"logged_in": True, "registry": registry}

            return {"logged_in": False}

        except Exception as e:
            return {"logged_in": False, "error": str(e)}

    def _check_aws(self) -> dict:
        """Check AWS credentials status."""
        try:
            result = subprocess.run(
                ["aws", "sts", "get-caller-identity", "--output", "json"],
                capture_output=True,
                text=True,
                timeout=10
            )

            if result.returncode == 0:
                import json
                data = json.loads(result.stdout)
                return {
                    "configured": True,
                    "identity": data.get("Arn", "").split("/")[-1],
                    "account": data.get("Account"),
                }

            return {"configured": False}

        except Exception as e:
            return {"configured": False, "error": str(e)}

    def get_teleport_login_command(self) -> list:
        """Get the tsh login command based on config."""
        cmd = [
            "tsh", "login",
            f"--proxy={self.config.teleport.proxy}",
            self.config.teleport.cluster
        ]

        if self.config.teleport.auth_method:
            cmd.append(f"--auth={self.config.teleport.auth_method}")

        return cmd


# Need to import Path for _check_docker
from pathlib import Path
