"""Views."""

import traceback

from esi.decorators import token_required

from django.contrib.auth.decorators import login_required, permission_required
from django.shortcuts import render

from allianceauth.services.hooks import get_extension_logger

from . import esi as pootest_esi

logger = get_extension_logger(__name__)

# ESI scopes required to read a corporation's structures. The authenticating
# character must additionally hold the Director or Station Manager role.
STRUCTURE_SCOPES = [
    "esi-corporations.read_structures.v1",
    "esi-universe.read_structures.v1",
    "esi-assets.read_corporation_assets.v1",
]


@login_required
@permission_required("pootest.basic_access")
def index(request):
    """Render index view."""
    context = {
        "text": "Hello, World! This is aa-pootest.",
        "page_title": "Welcome",
    }
    return render(request, "pootest/index.html", context)


@login_required
@permission_required("pootest.basic_access")
@token_required(scopes=STRUCTURE_SCOPES)
def structures(request, token):
    """List the structures owned by the corporation of the authenticated
    character, one per line.

    The character must be a Director or Station Manager of the corporation,
    otherwise ESI returns no data / a 403.
    """
    structure_list = []
    error = None
    error_detail = None
    error_traceback = None
    try:
        corporation_id = pootest_esi.get_corporation_id_for_character(
            token.character_id
        )
        structure_list = pootest_esi.fetch_corporation_structures(
            corporation_id, token
        )
    except Exception as exc:  # noqa: BLE001 - show the real error on the page
        # Full traceback also goes to the Alliance Auth log.
        logger.exception("Could not load corporation structures")

        response = getattr(exc, "response", None)
        status = getattr(response, "status_code", None)

        # ESI puts the real reason in the response body (e.g. a role error).
        body = getattr(response, "text", None) if response is not None else None
        if not body and response is not None:
            content = getattr(response, "content", None)
            if content:
                try:
                    body = content.decode("utf-8", "replace")
                except (AttributeError, UnicodeDecodeError):
                    body = str(content)

        detail_lines = []
        if status:
            detail_lines.append(f"HTTP status: {status}")
        detail_lines.append(f"Exception: {type(exc).__name__}: {exc}")
        if body:
            detail_lines.append(f"ESI response body: {body}")

        if status == 403:
            error = (
                f"ESI returned 403 Forbidden for character "
                f"'{token.character_name}'. That character must be a Director or "
                "Station Manager of its corporation. If you have multiple "
                "characters, make sure you pick the director on the token screen."
            )
        else:
            error = "Could not read structures from ESI. The actual error is shown below."

        error_detail = "\n".join(detail_lines)
        error_traceback = traceback.format_exc()

    context = {
        "page_title": "Corporation Structures",
        "structures": structure_list,
        "structure_count": len(structure_list),
        "error": error,
        "error_detail": error_detail,
        "error_traceback": error_traceback,
    }
    return render(request, "pootest/structures.html", context)
