import os
from pathlib import Path
from typing import Optional

import typer
from dotenv import load_dotenv


def load_jira_env(config_file: Optional[Path] = None) -> tuple[str, str, str]:
    """Load Jira credentials from config file or environment.

    Args:
        config_file: Optional path to configuration file.
                    Defaults to ~/.config/jps-jira-utils/.jira.env

    Returns:
        A tuple of (base_url, email, api_token).

    Raises:
        Exit: If any credentials are missing.
    """
    if config_file is None:
        env_path = Path.home() / ".config" / "jps-jira-utils" / ".jira.env"
    else:
        env_path = config_file.expanduser().resolve()

    if env_path.exists():
        load_dotenv(env_path)

    base_url = os.environ.get("JIRA_BASE_URL", "").strip().rstrip("/")
    email = os.environ.get("JIRA_EMAIL", "").strip()
    token = os.environ.get("JIRA_API_TOKEN", "").strip()

    if not all([base_url, email, token]):
        typer.echo("Error: Missing Jira credentials.", err=True)
        typer.echo("Required: JIRA_BASE_URL, JIRA_EMAIL, JIRA_API_TOKEN", err=True)
        typer.echo(f"Put them in {env_path} or export to shell", err=True)
        raise typer.Exit(code=1)

    return base_url, email, token
