# -*- coding: utf-8 -*-
# hub/ticket/ui/pages/archive_view_helpers.py

"""Вспомогательные функции построения представления архива."""

from __future__ import annotations

from domain import ArchiveRecordSnapshot, TicketDocumentSnapshot, TicketTaskSnapshot
from domain.ticket_constants import STATE_REFUSED, TICKET_STATE_COLORS, TICKET_STATE_NAMES
from ui.task_view_formatters import format_datetime, split_task_location


def record_to_task_snapshot(record: ArchiveRecordSnapshot) -> TicketTaskSnapshot:
    """Построить синтетический TicketTaskSnapshot для отрисовки карточки."""
    state_code = record.pre_archive_state_code
    return TicketTaskSnapshot(
        task_id=record.task_id,
        location=record.location,
        state_code=state_code,
        state_name=TICKET_STATE_NAMES.get(state_code, "Архив"),
        action_text=record.action_text,
        color_hex=TICKET_STATE_COLORS.get(state_code, record.color_hex),
        created_at=record.created_at,
        completed_at=record.completed_at,
        refused_from_state=record.refused_from_state,
        refusal_reason=record.refusal_reason,
        assigned_specialist=record.assigned_specialist,
        specialist_photo=record.specialist_photo,
        diagnostic_report_signed=record.diagnostic_report_signed,
        repair_report_signed=record.repair_report_signed,
        acceptance_report_signed=record.acceptance_report_signed,
        sequence_number=record.sequence_number,
    )


def cycle_token_from_record(record: ArchiveRecordSnapshot) -> str:
    """Получить cycle_token из created_at архивной записи."""
    if record.created_at is not None:
        return record.created_at.strftime("%Y%m%d_%H%M%S")
    return ""


def build_preview_lines(
    record: ArchiveRecordSnapshot,
    documents: list[TicketDocumentSnapshot],
) -> list[str]:
    """Собрать текст предпросмотра архивной записи."""
    institution, device, room = split_task_location(record.location)
    is_refused = record.pre_archive_state_code == STATE_REFUSED

    lines: list[str] = []
    seq = record.sequence_number or record.task_id
    lines.append(f"Задача #{seq}")
    lines.append(f"Статус: {record.pre_archive_state_name}")
    lines.append("")

    lines.append(f"Учреждение: {institution}")
    lines.append(f"Оборудование: {device}")
    lines.append(f"Кабинет: {room}")
    lines.append("")

    lines.append(f"Создана: {format_datetime(record.created_at)}")
    if record.completed_at is not None:
        label = "Отказано" if is_refused else "Завершена"
        lines.append(f"{label}: {format_datetime(record.completed_at)}")
    lines.append(f"Архивирована: {format_datetime(record.archived_at)}")
    lines.append("")

    lines.append("─── Ход работ ───")
    lines.append("")

    specialist = record.assigned_specialist.strip()
    lines.append(f"Специалист: {specialist or 'Не назначен'}")
    lines.append(
        f"Диагностика: {'Подписан' if record.diagnostic_report_signed else 'Не подписан'}"
    )
    lines.append(
        f"Ремонт: {'Подписан' if record.repair_report_signed else 'Не подписан'}"
    )
    lines.append(
        f"Приёмка: {'Подписан' if record.acceptance_report_signed else 'Не подписан'}"
    )
    lines.append("")

    if is_refused and record.refusal_reason:
        lines.append("─── Причина отказа ───")
        lines.append("")
        lines.append(record.refusal_reason)
        lines.append("")

    if documents:
        for doc in documents:
            _append_document_block(lines, doc)

    return lines


_BASE_PAYLOAD_KEYS = frozenset({
    "task_id", "institution", "room", "device", "location", "specialist",
})

_PAYLOAD_KEY_LABELS: dict[str, str] = {
    "initial_cause": "Первичное заключение",
    "actual_cause": "Вторичное заключение",
    "work_done": "Выполненные работы",
    "used_parts": "Использованные запчасти",
    "recommendations": "Рекомендации",
    "work_description": "Описание работ",
    "executor_signature": "Исполнитель",
    "customer_signature": "Заказчик",
}


def _append_document_block(
    lines: list[str], doc: TicketDocumentSnapshot,
) -> None:
    """Добавить блок документа без дублирования данных заголовка записи."""
    doc_date = format_datetime(doc.created_at)
    lines.append(f"─── {doc.title} ({doc_date}) ───")
    lines.append("")
    if doc.payload:
        for key, value in doc.payload.items():
            if not value or key in _BASE_PAYLOAD_KEYS:
                continue
            label = _PAYLOAD_KEY_LABELS.get(key, key)
            lines.append(f"{label}: {value}")
    elif doc.summary:
        lines.append(doc.summary)
    lines.append("")
