"""
Renders `OnboardingApiCallLog` rows into the chronological, human-readable
`.txt` export for the Super Admin "Export Onboarding Logs" feature.
"""
from __future__ import annotations

import json
from typing import List

from src.apps.merchant_onboarding.models.api_call_log import OnboardingApiCallLog

_DIVIDER = "=" * 80


def _format_json(value) -> str:
    if value is None:
        return "(none)"
    return json.dumps(value, indent=2, default=str)


def _format_headers(headers) -> str:
    if not headers:
        return "(none)"
    return "\n".join(f"{k}: {v}" for k, v in headers.items())


def build_export_text(logs: List[OnboardingApiCallLog]) -> str:
    """One divider-separated block per call, in the order `logs` is given
    (chronological). Renders every captured field for end-to-end tracing."""
    blocks = []
    for index, log in enumerate(logs, start=1):
        duration = f"{log.duration_ms} ms" if getattr(log, "duration_ms", None) is not None else "(n/a)"

        header_lines = [
            f"Timestamp: {log.created_at.strftime('%Y-%m-%d %H:%M:%S UTC')}",
            f"Sequence: #{index}",
            f"Service: {getattr(log, 'service', None) or '(unknown)'}",
            f"API: {getattr(log, 'api_name', None) or '(unknown)'}",
            f"Method: {log.method}",
            f"URL: {log.full_url}",
            f"Duration: {duration}",
        ]
        if getattr(log, "correlation_id", None):
            header_lines.append(f"Correlation ID: {log.correlation_id}")

        response_section = (
            f"Response:\n"
            f"Status: {log.response_status if log.response_status is not None else '(no response)'}\n\n"
            f"Headers:\n{_format_headers(log.response_headers)}\n\n"
            f"Body:\n{_format_json(log.response_body)}"
        )
        if log.error_message:
            response_section += f"\n\nError:\n{log.error_message}"

        block = (
            f"{_DIVIDER}\n"
            + "\n".join(header_lines)
            + "\n\n"
            f"Request:\n"
            f"Headers:\n{_format_headers(log.request_headers)}\n\n"
            f"Body:\n{_format_json(log.request_body)}\n\n"
            f"{response_section}\n"
            f"{_DIVIDER}"
        )
        blocks.append(block)
    return "\n\n".join(blocks) + "\n"
