"""``/api/ta1-acks`` — list & detail endpoints for persisted TA1 envelopes.

TA1 is the interchange-control ACK (ISA/IEA acknowledgement). It's a
single segment, no functional group, no transaction set. Cyclone
persists the parsed fields plus a synthetic ``source_batch_id`` so the
row can sit alongside the 999 / 277CA ack rows without special-casing.

The detail endpoint also reconstructs the TA1 segment string
(``TA1*...~``) so the operator can copy it into a downstream tool.
"""
from __future__ import annotations

from typing import Any

from fastapi import APIRouter, HTTPException, Query

from cyclone import db
from cyclone.store import store

router = APIRouter()


def _ta1_to_ui(row: db.Ta1Ack) -> dict:
    """Render a Ta1Ack row for the UI (list endpoint shape)."""
    return {
        "id": row.id,
        "control_number": row.control_number,
        "ack_code": row.ack_code,
        "note_code": row.note_code,
        "interchange_date": row.interchange_date.isoformat()
            if row.interchange_date else None,
        "interchange_time": row.interchange_time,
        "sender_id": row.sender_id,
        "receiver_id": row.receiver_id,
        "source_batch_id": row.source_batch_id,
        "parsed_at": row.parsed_at.isoformat() if row.parsed_at else None,
    }


def _serialize_ta1_from_row(row: db.Ta1Ack) -> str:
    """Reconstruct a TA1 segment from the persisted flat row (for the detail endpoint)."""
    date_s = row.interchange_date.strftime("%y%m%d") if row.interchange_date else ""
    return (
        f"TA1*{row.control_number}*{date_s}*{row.interchange_time or ''}*"
        f"{row.ack_code}*{row.note_code or ''}~"
    )


@router.get("/api/ta1-acks")
def list_ta1_acks_endpoint(
    limit: int = Query(100, ge=1, le=1000),
) -> Any:
    """Return the list of persisted TA1 ACKs, newest first.

    Mirrors :func:`cyclone.api_routers.acks.list_acks_endpoint` — fetches all
    rows then slices in Python so the ``total`` field reflects the full row
    count regardless of the ``limit`` cap.
    """
    rows = store.list_ta1_acks()
    items = [_ta1_to_ui(r) for r in rows[:limit]]
    return {
        "total": len(rows),
        "items": items,
    }


@router.get("/api/ta1-acks/{ack_id}")
def get_ta1_ack_endpoint(ack_id: int) -> dict:
    """Return one persisted TA1 ACK row with its parsed detail."""
    row = store.get_ta1_ack(ack_id)
    if row is None:
        raise HTTPException(status_code=404, detail=f"TA1 ACK {ack_id} not found")
    body = _ta1_to_ui(row)
    body["raw_ta1_text"] = _serialize_ta1_from_row(row)
    body["raw_json"] = row.raw_json
    return body
