from __future__ import annotations

import json

from g_gremlin.auth.types import AuthResolution


def format_auth_resolution(resolution: AuthResolution, *, json_output: bool = False) -> str:
    safe = resolution.to_safe_dict()
    if json_output:
        return json.dumps(safe, indent=2, sort_keys=True)

    lines = [
        f"surface: {safe['surface']}",
        f"integration: {safe['integration']}",
        f"selected_source: {safe['selected_source']}",
        f"api_base: {safe['api_base'] or '-'}",
        f"workspace_id: {safe['workspace_id'] or '-'}",
        f"mode: {safe['mode'] or '-'}",
        f"refresh_strategy: {safe['refresh_strategy']}",
    ]
    if safe["warnings"]:
        lines.append(f"warnings: {', '.join(safe['warnings'])}")
    if safe["headers"]:
        lines.append(f"headers: {safe['headers']}")
    if safe["credentials"]:
        lines.append(f"credentials: {safe['credentials']}")
    lines.append("attempts:")
    for attempt in safe["attempts"]:
        field = attempt.get("field") or "auth"
        lines.append(
            f"- {field}: {attempt['source']} {attempt['outcome']} ({attempt['detail']})"
        )
    return "\n".join(lines)
