"""Lightweight configuration for sphinx-lookup.

Reads credentials from (in priority order):
1. Environment variables
2. ~/.sphinx-lookup.env file
3. .env in current directory

Authentication modes:
- Admin: SUPABASE_URL + SUPABASE_KEY (service_role)
- Team member: SUPABASE_URL + SUPABASE_ANON_KEY + SPHINX_API_KEY
"""

from __future__ import annotations

import os
from dataclasses import dataclass
from pathlib import Path

from dotenv import dotenv_values


CONFIG_FILE = Path.home() / ".sphinx-lookup.env"


@dataclass
class LookupConfig:
    supabase_url: str
    supabase_key: str  # service_role key (for admin)
    anon_key: str  # anon key (for team members)
    api_key: str  # personal API key (for team members)

    @classmethod
    def load(cls) -> LookupConfig:
        """Load config from env vars and dotenv files."""
        # Layer 1: .env in cwd (lowest priority)
        values: dict[str, str | None] = {}
        cwd_env = Path.cwd() / ".env"
        if cwd_env.exists():
            values.update(dotenv_values(cwd_env))

        # Layer 2: ~/.sphinx-lookup.env
        if CONFIG_FILE.exists():
            values.update(dotenv_values(CONFIG_FILE))

        # Layer 3: actual environment variables (highest priority)
        for key in ("SUPABASE_URL", "SUPABASE_KEY", "SUPABASE_ANON_KEY", "SPHINX_API_KEY"):
            env_val = os.environ.get(key)
            if env_val:
                values[key] = env_val

        return cls(
            supabase_url=values.get("SUPABASE_URL", ""),
            supabase_key=values.get("SUPABASE_KEY", ""),
            anon_key=values.get("SUPABASE_ANON_KEY", ""),
            api_key=values.get("SPHINX_API_KEY", ""),
        )

    @property
    def is_configured(self) -> bool:
        """Check if we have valid credentials (either mode)."""
        has_url = bool(self.supabase_url)
        # Admin mode: service_role key
        # Team mode: anon key + personal API key
        has_admin_auth = bool(self.supabase_key)
        has_team_auth = bool(self.anon_key and self.api_key)
        return has_url and (has_admin_auth or has_team_auth)

    @property
    def auth_mode(self) -> str:
        """Return the authentication mode being used."""
        if self.supabase_key:
            return "admin"
        elif self.anon_key and self.api_key:
            return "team_member"
        return "none"

    def save(self) -> None:
        """Write current config to ~/.sphinx-lookup.env."""
        lines = [f"SUPABASE_URL={self.supabase_url}\n"]

        if self.supabase_key:
            lines.append(f"SUPABASE_KEY={self.supabase_key}\n")

        if self.anon_key:
            lines.append(f"SUPABASE_ANON_KEY={self.anon_key}\n")

        if self.api_key:
            lines.append(f"SPHINX_API_KEY={self.api_key}\n")

        CONFIG_FILE.write_text("".join(lines))
        CONFIG_FILE.chmod(0o600)
