"""Credential management for Personal Assistant MCP."""

import json
import os
import stat
from dataclasses import dataclass, field
from pathlib import Path


API_URL = "https://gogetthingsdone.com"
GOOGLE_CLIENT_ID = "98377573861-aojaqd39a5pmj86mtdgk25hqhtt0s01m.apps.googleusercontent.com"
GOOGLE_CLIENT_SECRET = "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"

CONFIG_DIR = Path.home() / ".config" / "personal-assistant-mcp"
CREDENTIALS_FILE = CONFIG_DIR / "credentials.json"


@dataclass
class Credentials:
    auth_method: str  # "email" or "google"
    api_url: str = API_URL
    # Email/password auth
    email: str = ""
    password: str = ""
    # Google auth — backend JWT tokens obtained during setup
    access_token: str = ""
    refresh_token: str = ""


def load_credentials() -> Credentials:
    """Load credentials from the config file.

    Raises FileNotFoundError if the file doesn't exist.
    Raises ValueError if the file is malformed.
    """
    if not CREDENTIALS_FILE.exists():
        raise FileNotFoundError(
            "Credentials not found. Run 'personal-assistant-mcp setup' first."
        )

    data = json.loads(CREDENTIALS_FILE.read_text())

    auth_method = data.get("auth_method", "email")

    if auth_method == "email":
        missing = [k for k in ("email", "password") if not data.get(k)]
        if missing:
            raise ValueError(
                f"Credentials file is missing fields: {', '.join(missing)}. "
                "Run 'personal-assistant-mcp setup' to reconfigure."
            )
        return Credentials(
            auth_method="email",
            email=data["email"],
            password=data["password"],
        )

    elif auth_method == "google":
        if not data.get("refresh_token"):
            raise ValueError(
                "Credentials file is missing refresh_token. "
                "Run 'personal-assistant-mcp setup' to reconfigure."
            )
        return Credentials(
            auth_method="google",
            access_token=data.get("access_token", ""),
            refresh_token=data["refresh_token"],
        )

    else:
        raise ValueError(
            f"Unknown auth method: {auth_method}. "
            "Run 'personal-assistant-mcp setup' to reconfigure."
        )


def save_credentials_email(email: str, password: str) -> None:
    """Save email/password credentials."""
    _save({
        "auth_method": "email",
        "email": email,
        "password": password,
    })


def save_credentials_google(access_token: str, refresh_token: str) -> None:
    """Save Google OAuth credentials (backend JWT tokens)."""
    _save({
        "auth_method": "google",
        "access_token": access_token,
        "refresh_token": refresh_token,
    })


def _save(data: dict) -> None:
    """Write credentials to disk with restricted permissions."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    CREDENTIALS_FILE.write_text(json.dumps(data, indent=2))
    os.chmod(CREDENTIALS_FILE, stat.S_IRUSR | stat.S_IWUSR)
