openapi: 3.0.3
info:
  title: exdata API
  version: 1.0.0
  description: >
    exdata document processing and extraction API.
servers:
  - url: https://api.exdata.app/v1
    description: Production API
security:
  - bearerAuth: []
paths:
  /ping:
    get:
      summary: Check API authentication
      operationId: ping
      parameters:
        - $ref: "#/components/parameters/RequestId"
      responses:
        "200":
          description: Authenticated API status.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
          content:
            application/json:
              schema:
                type: object
                required: [status]
                properties:
                  status:
                    type: boolean
                    example: true
        "429":
          $ref: "#/components/responses/RateLimited"
  /documents:
    get:
      summary: List documents
      operationId: listDocuments
      parameters:
        - $ref: "#/components/parameters/RequestId"
        - name: sort
          in: query
          example: -created_at
          schema:
            type: string
            enum: [created_at, -created_at]
          description: Sort by creation time ascending or descending.
        - name: per_page
          in: query
          example: 25
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 100
        - name: extraction_profile
          in: query
          required: false
          schema:
            type: string
            maxLength: 100
            example: de.energy.supply-invoice
          description: Filter documents by the extraction profile selected at upload.
        - name: review_status
          in: query
          required: false
          schema:
            $ref: "#/components/schemas/ProfileEffectiveOutcome"
          description: Filter documents by the current outcome of their effective specialized profile result. A failed retry does not replace an earlier usable result; when every attempt failed, the latest failure is effective.
        - name: handoff_status
          in: query
          required: false
          schema:
            $ref: "#/components/schemas/ProfileHandoffStatus"
          description: Filter documents by the current downstream handoff state of their effective specialized profile result. A failed retry does not replace an earlier usable result.
      responses:
        "200":
          description: Paginated document list.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/PaginatedDocuments"
        "429":
          $ref: "#/components/responses/RateLimited"
    post:
      summary: Upload a document
      description: >
        Upload a supported file for asynchronous processing. The multipart
        `file` schema lists all supported extensions, limits, and format
        behavior. `processing_mode` defaults to `extraction`. A live
        extraction applies the applicable profile rate to its first
        10-page band before processing begins. Generic extraction has a one-credit
        rate. `de.energy.supply-invoice` currently costs 3 credits per started
        band, so 1-10 pages use 3 credits and 11-20 use 6. A specialized
        profile records its `credit_cost`, expressed as credits
        per started 10-page band. After analysis determines the page
        count, final usage is calculated as `credit_cost` multiplied by the
        number of started bands; for example, a rate of three uses 3 credits for
        1-10 pages and 6 credits for 11-20. The run keeps that total when a
        usable result or retrievable extracted fields remain. A terminal
        processing error that leaves neither, including
        preprocessing failure, returns the applied credits. If an additional
        page band cannot be covered after this endpoint has returned `201`, the
        document becomes blocked with
        `blocked_reason=page_band_insufficient_credits` and the initial
        credits are returned. Test-mode and thumbnail-only uploads have
        zero net credit usage. Reprocessing after an already completed usable
        result also has zero incremental usage; when a fully
        returned failure is reprocessed, the first later attempt that leaves a
        usable result or retrievable extracted fields receives a new
        page-band charge. Reprocessing an existing document
        preserves the profile version, processing settings, and credit rate
        recorded for that document. Profile setting changes apply to new
        uploads only. Set
        `processing_mode=analysis` to run the same lifecycle and credit calculation
        without running AI or structured extraction, optionally choosing the
        pages to process with `pages`. Set
        `processing_mode=thumbnail` to generate only a JPEG thumbnail without
        OCR, AI, structured extraction, persisted previews, or an extraction
        run. `processing_lane` defaults to `standard`. The delayed `batch`
        lane is available to eligible accounts and uses lower-priority capacity;
        it suits backfills and other work where longer processing waits are
        acceptable. If batch is unavailable for the account, the upload returns
        `422` with `code=validation_failed` and a `processing_lane` validation
        error. Both lanes return the same
        result shape and lifecycle webhooks. In thumbnail
        mode, videos use a representative decoded frame. Supported video
        formats are MP4, M4V, MOV, WebM, OGV, and OGG. Video containers must
        include a decodable video stream, and decoded frames must not exceed
        33177600 pixels; audio-only files fail during processing, and oversized
        video files fail during processing.
      operationId: uploadDocument
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
        - $ref: "#/components/parameters/RequestId"
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file:
                  $ref: "#/components/schemas/SupportedUploadFile"
                text:
                  type: string
                  nullable: true
                  maxLength: 262144
                  x-maxBytes: 262144
                  description: Additional source text or business context treated as document evidence, not extraction instructions. Maximum 262144 UTF-8 bytes (256 KiB). This field is rejected with `processing_mode=validation` because validation evaluates only the uploaded PDF or XML.
                custom_types:
                  type: array
                  nullable: true
                  maxItems: 50
                  items:
                    type: string
                    maxLength: 100
                  description: Optional type extensions for workflows beyond the standard document types. Standard types are invoice, credit-note, reminder, salary-statement, bank-statement, contract, balance-sheet, tax-assessment-note, timesheet, letter, and other. Validation mode does not use or persist these extensions.
                requester:
                  type: string
                  nullable: true
                  maxLength: 255
                  description: Caller reference, integration name, or request source. For `de.energy.supply-invoice`, exdata retains this as upload metadata and it does not affect profile extraction.
                locale:
                  type: string
                  nullable: true
                  enum: [en, de, fr, es, it, pl, nl, pt, ro]
                  example: en
                  description: Selected document language. Omit it to use the account's default document language. The `de.energy.supply-invoice` profile requires `de`; another locale returns `422`.
                processing_mode:
                  type: string
                  enum: [extraction, analysis, validation, thumbnail]
                  default: extraction
                  description: "Processing requested for this upload. `extraction` runs the document extraction lifecycle and applies the applicable per-started-10-page-band rate for live uploads: the final total is kept when a usable result or retrievable extracted fields remain. `analysis` runs the same lifecycle without the AI step and without structured extraction: it returns the thumbnail, persisted previews, page count, extracted text, and structured e-invoice detection, and `extractions` completes as an empty array. `validation` accepts only PDF or XML, performs structured-invoice detection, XML validation, and required PDF/XML linkage without AI, general extraction, persisted previews, or a thumbnail, and returns the result in `latest_extraction_run.quality.structured`; for a PDF with valid embedded invoice XML, bounded rendered OCR is required for visible linkage, and a searchable or hidden native text layer does not establish a passing result. Analysis and validation report `ai_processing=false` and use the same credit calculation as extraction. `thumbnail` only generates a JPEG thumbnail, does not create persisted previews or extraction results, and has zero credit usage."
                processing_lane:
                  type: string
                  enum: [standard, batch]
                  default: standard
                  description: Processing priority selected for this upload. `standard` is the default lane. `batch` is available to eligible accounts; it uses constrained lower-priority capacity, can take longer to start, and preserves the same processing stages, results, polling behavior, and lifecycle webhooks. If batch is unavailable for the account, the upload returns `422` with `code=validation_failed` and a `processing_lane` validation error.
                pages:
                  type: string
                  maxLength: 255
                  description: "Pages to process, as a comma-separated list of `first`, `last`, `all`, or 1-based page numbers. Only valid with `processing_mode=analysis`; every other mode needs the whole document and returns `422`. Supported for PDF uploads and for single-page file types such as images, where every selection collapses to the one page; Word, TIFF, email, and video uploads return `422`. Unrequested pages are not processed: they are not OCRed, contribute no text to the result, and are not charged, so a smaller selection returns sooner and costs less. The thumbnail and the first-page preview are always generated. Page numbers beyond the document are ignored; a selection whose pages all lie beyond the document processes the first page. When the document's page count cannot be read, `last` resolves within the documented visual PDF processing limit. Omitting the field processes every page."
                  example: first,last
                allow_ai_processing:
                  type: boolean
                  default: true
                  description: Optional extraction-mode flag. Multipart values may be `true`, `false`, `1`, or `0`; the words are case-insensitive. In `extraction` mode, `false` disables AI only; OCR, non-AI structured extraction, previews, thumbnail generation, and normal page-band credit calculation still apply. `processing_mode=thumbnail`, `processing_mode=analysis`, and `processing_mode=validation` take precedence over either value and report `ai_processing=false`.
                extraction_profile:
                  type: string
                  nullable: true
                  example: de.energy.supply-invoice
                  x-extensible-enum: [generic, de.energy.supply-invoice]
                  description: Optional registered extraction profile selected explicitly for this upload. Omit this field or send `generic` for generic extraction. Validation mode accepts only the generic profile; selecting a sector profile with validation returns `422`. Every active account can select `de.energy.supply-invoice` for German electricity and natural-gas supply invoices; it accepts PDF uploads and requires `locale=de`, extraction mode, and AI enabled. Another document locale returns `422`. New energy uploads use profile version 2.0.1 and schema version 2.0.0, with a current rate of 3 credits per started 10-page band (3 for 1-10 pages and 6 for 11-20). The returned payload separates packet metadata from one source-ordered result per independently issued invoice and covers invoice identity, parties, supply points, tariffs, operators, registers, readings, consumption, gas conversion, charge lines, taxes, settlement balances, due dates, and payment data. A single-invoice PDF still returns one item in `invoices`; a source-verified non-invoice returns an empty `invoices` array with an unsupported outcome. Accepted results expose canonical JSON and invoice-line CSV exports. The applicable rate and billing details are returned in extraction-run metadata. The profile applies conservative source-backed invoice-date and billing-period recovery, recognizes advance-payment notices as non-invoices, and keeps ambiguous page ownership or mixed-utility scope in review. The selected profile determines the version, processing settings, and applicable per-band rate recorded for the run. Upload, polling, result, review, and export operations use the document endpoints; the complete profile payload is returned by the extractions endpoint and there is no separate top-level profile-result route.
      responses:
        "201":
          description: Document accepted for asynchronous processing. Extraction-lifecycle modes apply the first 1-10-page band at the run's recorded `credit_cost`, or wait for a pending automatic credit top-up with `processing_stage=waiting_for_auto_top_up`. Generic extraction, analysis, and validation use one credit per band; the current German energy profile uses three. When the page count is readable at upload, such as PDF and TIFF, `number_of_pages` is already populated and the account was checked against the bands that count requires, so a `201` means the available credits covered the initial calculation at that moment. Final page-band usage can be updated after processing resolves an authoritative count, so a `201` is not a guarantee. If available credits do not cover an additional band, polling and the `document.blocked` webhook report `blocked_reason=page_band_insufficient_credits`, and the credits for that run are returned for zero net usage. A completed validation result is published only after that final page-band total is covered, so a validation run blocked for page-band funding exposes no completed structured assessment. Thumbnail mode is accepted without credit usage. The selected standard or batch lane is reported in `processing_lane`. Any standard-lane upload, including thumbnail mode, made while your account is already at its concurrent processing limit is accepted with `processing_stage=waiting_for_capacity` and starts automatically as earlier documents finish. Continue polling the document or wait for lifecycle webhooks.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DocumentResource"
              examples:
                processingQueued:
                  summary: Extraction accepted
                  value:
                    data:
                      id: 123
                      status: pending
                      processing_mode: extraction
                      processing_lane: standard
                      processing_stage: queued
                      latest_extraction_run:
                        credits_charged: 1
                batchProcessingQueued:
                  summary: Batch extraction accepted
                  value:
                    data:
                      id: 125
                      status: pending
                      processing_mode: extraction
                      processing_lane: batch
                      processing_stage: queued
                      latest_extraction_run:
                        credits_charged: 1
                validationQueued:
                  summary: Structured-invoice validation accepted
                  value:
                    data:
                      id: 126
                      status: pending
                      processing_mode: validation
                      processing_lane: standard
                      processing_stage: queued
                      ai_processing: false
                      latest_extraction_run:
                        credits_charged: 1
                thumbnailQueued:
                  summary: Thumbnail generation accepted
                  value:
                    data:
                      id: 124
                      status: pending
                      processing_mode: thumbnail
                      processing_lane: standard
                      processing_stage: queued
                      ai_processing: false
                      latest_extraction_run: null
                waitingForAutoTopUp:
                  summary: Waiting for automatic credit top-up
                  value:
                    data:
                      id: 123
                      status: pending
                      processing_mode: extraction
                      processing_lane: standard
                      processing_stage: waiting_for_auto_top_up
        "422":
          $ref: "#/components/responses/ValidationError"
        "409":
          $ref: "#/components/responses/IdempotencyConflict"
        "429":
          $ref: "#/components/responses/UploadRateLimited"
        "503":
          $ref: "#/components/responses/UploadUnavailable"
        "402":
          description: Extraction, analysis, or validation mode. Available credits do not cover the document, so processing does not begin and no credit is charged. This covers both the initial page band at the run's recorded `credit_cost` and, when the page count is readable at upload, the additional bands that count requires. A `402` therefore replaces the asynchronous `page_band_insufficient_credits` block for those formats; for formats whose page count is resolved only during processing, that asynchronous block can still apply after a `201`. Thumbnail mode has zero credit usage and is not blocked by the extraction credit balance.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InsufficientCreditsError"
  /x402/extractions:
    post:
      summary: Upload a document with x402 payment
      description: >
        Anonymous x402 extraction is currently unavailable and this endpoint
        returns `503`. Use authenticated REST uploads instead. The request and
        success schemas below document the response shape for this endpoint. The multipart
        `file` schema lists all supported extensions, limits, and format
        behavior. Supported video formats are MP4, M4V, MOV, WebM, OGV, and
        OGG. Video containers must include a decodable video stream, and
        decoded frames must not exceed 33177600 pixels; audio-only files fail
        during processing, and oversized video files fail during processing.
      operationId: createAnonymousX402Extraction
      security: []
      parameters:
        - $ref: "#/components/parameters/PaymentSignature"
        - $ref: "#/components/parameters/RequestId"
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file:
                  $ref: "#/components/schemas/SupportedUploadFile"
                text:
                  type: string
                  nullable: true
                  maxLength: 262144
                  x-maxBytes: 262144
                  description: Additional source text or business context treated as document evidence, not extraction instructions. Maximum 262144 UTF-8 bytes (256 KiB).
                custom_types:
                  type: array
                  nullable: true
                  maxItems: 50
                  items:
                    type: string
                    maxLength: 100
                  description: Optional type extensions for workflows beyond the standard document types.
                requester:
                  type: string
                  nullable: true
                  maxLength: 255
                  description: Caller reference, integration name, or request source.
                locale:
                  type: string
                  nullable: true
                  enum: [en, de, fr, es, it, pl, nl, pt, ro]
                  example: en
                  description: Selected document language. Omit it to use the account's default document language.
                allow_ai_processing:
                  type: boolean
                  default: true
                  description: Optional processing flag. Multipart values may be `true`, `false`, `1`, or `0`; the words are case-insensitive. Most integrations omit this field.
      responses:
        "200":
          description: Same payment and same request replayed; the cached anonymous extraction response is returned.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
            X402-Replayed:
              description: Present with value `true` when the response is an idempotent replay of a completed x402 payment.
              schema:
                type: string
                enum: ["true"]
            PAYMENT-RESPONSE:
              description: Base64-encoded x402 SettlementResponse JSON for the completed payment.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/X402ExtractionAccepted"
        "201":
          description: Payment completed, document accepted, and anonymous polling access issued.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
            PAYMENT-RESPONSE:
              description: Base64-encoded x402 SettlementResponse JSON containing the payment result.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/X402ExtractionAccepted"
        "400":
          description: The supplied x402 payment-identifier extension is malformed.
          headers:
            PAYMENT-REQUIRED:
              description: Base64-encoded x402 PaymentRequired JSON.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorEnvelope"
        "402":
          description: x402 payment is required, failed verification, or payment processing failed.
          headers:
            PAYMENT-REQUIRED:
              description: Base64-encoded x402 PaymentRequired JSON.
              schema:
                type: string
            PAYMENT-RESPONSE:
              description: Base64-encoded x402 SettlementResponse JSON when payment processing was attempted.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/X402PaymentError"
        "409":
          description: The x402 payment was already used for a different extraction request, is still processing, or references a completed extraction that is no longer available.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorEnvelope"
        "422":
          $ref: "#/components/responses/ValidationError"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          description: Anonymous x402 extraction is currently unavailable. Use authenticated REST uploads instead.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorEnvelope"
  /x402/extractions/{document}:
    get:
      summary: Retrieve an anonymous x402 extraction
      operationId: getAnonymousX402Extraction
      security: []
      parameters:
        - $ref: "#/components/parameters/DocumentId"
        - $ref: "#/components/parameters/X402AccessToken"
        - $ref: "#/components/parameters/X402AccessTokenQuery"
        - $ref: "#/components/parameters/PaymentSignature"
        - $ref: "#/components/parameters/RequestId"
      responses:
        "200":
          description: Document metadata, status, and completed extraction fields when available.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/X402ExtractionAccepted"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
  /documents/{document}:
    get:
      summary: Retrieve a document
      operationId: getDocument
      parameters:
        - $ref: "#/components/parameters/DocumentId"
        - $ref: "#/components/parameters/RequestId"
      responses:
        "200":
          description: Document metadata, processing mode, status, and completed results when available. A completed thumbnail-only document has a thumbnail URL, no extraction run, and no preview or extraction results.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DocumentResource"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
    delete:
      summary: Delete a document
      operationId: deleteDocument
      parameters:
        - $ref: "#/components/parameters/DocumentId"
        - $ref: "#/components/parameters/RequestId"
      responses:
        "204":
          description: The document resource and stored extracted values are no longer available. The service attempts to remove the ordinary source file, thumbnail, and previews, but a `204` response does not attest to object-storage deletion. Unconfirmed file deletions are retried automatically. A separately retained quality-evidence sample may remain until its documented retention expiry.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: The current live extraction is still active, so the document cannot be deleted yet. Wait for a terminal document status and retry; delayed processing can take longer, so poll the document status rather than retrying on a short interval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorEnvelope"
        "429":
          $ref: "#/components/responses/RateLimited"
  /documents/{document}/thumbnail:
    get:
      summary: Download document thumbnail
      description: Download the generated JPEG thumbnail. For video uploads, including thumbnail-only uploads, the thumbnail is a representative frame extracted from the video. The resource becomes available after successful thumbnail generation.
      operationId: getDocumentThumbnail
      parameters:
        - $ref: "#/components/parameters/DocumentId"
        - $ref: "#/components/parameters/RequestId"
      responses:
        "200":
          description: JPEG thumbnail binary. For video uploads, this is a representative frame extracted from the video.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
          content:
            image/jpeg:
              schema:
                type: string
                format: binary
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/DocumentStorageUnavailable"
  /documents/{document}/previews:
    get:
      summary: List document previews
      description: List persisted preview files. Every supported e-invoice receives one human-readable HTML invoice visualization in CII, UBL, and ZUGFeRD 1.0 COMFORT syntax, so the same invoice layout is returned regardless of the source format. Locally validated Extension XRechnung 3.0 invoices additionally keep their source-ordered recursive invoice-line view. For exceptionally large line sets or repeatable review sections, the affected content is shown as a clearly labelled bounded prefix so browser rendering remains safe; the original XML remains unchanged. This HTML file is the canonical preview; the accompanying JPEG is only a representative thumbnail and visual fallback. Remaining safe XML uses a pretty-printed XML fallback. The visualization is labelled in the selected document locale. A completed document created with `processing_mode=thumbnail` returns an empty `data` array because thumbnail mode does not generate previews.
      operationId: listDocumentPreviews
      parameters:
        - $ref: "#/components/parameters/DocumentId"
        - $ref: "#/components/parameters/RequestId"
      responses:
        "200":
          description: Preview metadata for a document.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/Preview"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
  /documents/{document}/extractions:
    get:
      summary: List document extractions
      description: Returns the normalized field map. For documents uploaded with a specialized extraction profile, the response also contains the effective profile result under `sector_extraction`; there is no separate top-level profile-result route. The profile determines the shapes of `machine_payload`, `effective_payload`, validation details, evidence, and exports. German energy supply invoices are the currently available specialized profile. A failed retry does not replace an earlier usable result, while the latest failure is returned when no usable result exists. Selected generic fields in `data` follow reviewed values from `effective_payload`. Structured extraction does not run in thumbnail, analysis, or validation mode, so a completed document in any of those modes returns an empty `data` array. API tokens require `documents:read`.
      operationId: listDocumentExtractions
      parameters:
        - $ref: "#/components/parameters/DocumentId"
        - name: include
          in: query
          required: false
          example: evidence
          schema:
            type: string
            enum: [evidence]
          description: Set to `evidence` to include profile evidence and run-bound `evidence_pages` descriptors. A descriptor exposes a preview URL only when the cited artifact for that exact extraction run is still safely available.
        - $ref: "#/components/parameters/RequestId"
      responses:
        "200":
          description: Flat extracted fields plus an optional specialized profile result under `sector_extraction`.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
            ETag:
              description: Current profile-result entity tag when a specialized result is present. Send this value as `If-Match` when posting a review decision.
              schema:
                type: string
                example: '"extraction-result-789-v0"'
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    oneOf:
                      - $ref: "#/components/schemas/Extractions"
                      - type: array
                        maxItems: 0
                        description: Empty array returned for a completed thumbnail-only, analysis, or validation document.
                  sector_extraction:
                    $ref: "#/components/schemas/SectorExtraction"
                    description: Present when a finalized specialized profile result is selected for delivery. This includes the canonical failed result returned for an error document when no usable earlier profile result exists. The `sector_extraction` envelope is profile-neutral. Generic extraction responses omit it.
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
  /documents/{document}/extraction-runs/{extractionRun}/pages/{physicalPage}/preview:
    get:
      summary: Download an extraction evidence page preview
      operationId: downloadDocumentExtractionEvidencePagePreview
      description: Downloads one protected page artifact cited by a profile result. Use only URLs returned by `sector_extraction.evidence_pages`; every URL is bound to the document, the exact immutable extraction run, and the one-based physical page. The endpoint never falls back to a newer or older run. An unavailable, expired, missing, unsafe, or account-mismatched artifact fails closed. API tokens require `documents:read`.
      parameters:
        - $ref: "#/components/parameters/DocumentId"
        - $ref: "#/components/parameters/ExtractionRunId"
        - $ref: "#/components/parameters/PhysicalPage"
        - $ref: "#/components/parameters/RequestId"
      responses:
        "200":
          description: "Inline binary page artifact. The response uses `Cache-Control: private, no-store` and the stored artifact's safe content type."
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
            Content-Disposition:
              description: Inline filename for the cited page artifact.
              schema:
                type: string
                example: inline; filename="1.jpg"
            Cache-Control:
              description: Private no-store caching policy.
              schema:
                type: string
                example: private, no-store
          content:
            image/jpeg:
              schema:
                type: string
                format: binary
            image/png:
              schema:
                type: string
                format: binary
            image/gif:
              schema:
                type: string
                format: binary
            image/webp:
              schema:
                type: string
                format: binary
            application/pdf:
              schema:
                type: string
                format: binary
            application/octet-stream:
              schema:
                type: string
                format: binary
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
  /documents/{document}/exports/{projection}:
    get:
      summary: Download a document profile export
      operationId: downloadDocumentProfileExport
      description: Downloads one projection registered by the document's extraction profile. Use the route, version, and `available` flag returned in `sector_extraction.exports`; each profile projection owns its readiness policy after the result is finalized. German energy full-invoice profile versions 2.0.0 and 2.0.1 register `canonical.json` for the complete packet-shaped effective payload and `invoice-lines.csv` for one row per charge line across all returned invoices. Both require an accepted effective outcome and accepted handoff. API tokens require `documents:read`.
      parameters:
        - $ref: "#/components/parameters/DocumentId"
        - $ref: "#/components/parameters/ProfileProjection"
        - $ref: "#/components/parameters/RequestId"
      responses:
        "200":
          description: Versioned profile export. Content type and filename are defined by the selected projection.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
            ETag:
              description: Entity tag of the exact profile result used to render the export.
              schema:
                type: string
                example: '"extraction-result-789-v1"'
            X-Projection-Version:
              description: Versioned projection contract selected by the profile.
              schema:
                type: string
                example: de-energy-canonical-json:2.0.0
            Content-Disposition:
              description: Attachment filename generated by the selected projection.
              schema:
                type: string
                example: attachment; filename="german-energy-invoice-123-canonical.json"
            Cache-Control:
              description: Private no-store caching policy.
              schema:
                type: string
                example: private, no-store
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/GermanEnergyCanonicalExport"
              description: UTF-8 deterministic JSON for `canonical.json` containing profile identity, outcomes, packet metadata, every invoice result, and nested field evidence for audit use.
            text/csv:
              schema:
                $ref: "#/components/schemas/GermanEnergyInvoiceLinesCsv"
              description: UTF-8 CSV for `invoice-lines.csv`, with one row per canonical charge line. The first four columns identify the invoice and its page range inside the uploaded PDF.
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: The document, effective profile result, or requested projection is not available to this account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorEnvelope"
        "409":
          description: The extraction run is not finalized or the selected projection is not ready.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ProfileExportNotReadyError"
        "429":
          $ref: "#/components/responses/RateLimited"
  /documents/exports/{projection}:
    get:
      summary: Download a deterministic batch profile export
      operationId: downloadDocumentProfileExportBatch
      description: "Downloads one account-scoped projection for 1-100 distinct documents when the selected profile registers a compatible batch projection. The complete set fails closed: every ID must belong to the caller's account, every result's extraction run must be finalized, every result must satisfy the selected projection's batch-readiness policy, and every result must expose the same batch-capable projection implementation and version. German energy full-invoice profile versions 2.0.0 and 2.0.1 support batch `invoice-lines.csv`; every result must have an accepted effective outcome and accepted handoff. Unknown and cross-account IDs return the same `404` without partial output or ownership disclosure. Documents are rendered in ascending document-ID order; invoices remain in source order inside each document, and charge-line order is preserved inside each invoice. API tokens require `documents:read`."
      parameters:
        - $ref: "#/components/parameters/ProfileProjection"
        - name: document_ids[]
          in: query
          required: true
          style: form
          explode: true
          example: [123, 456]
          schema:
            type: array
            minItems: 1
            maxItems: 100
            uniqueItems: true
            items:
              type: integer
              minimum: 1
          description: One to 100 distinct document IDs. Repeat `document_ids[]` for each document; request order does not affect export order.
        - $ref: "#/components/parameters/RequestId"
      responses:
        "200":
          description: Deterministic versioned batch projection for the complete requested document set.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
            ETag:
              description: Composite entity tag derived from the projection key and version plus the ordered document, result, and result-ETag identities.
              schema:
                type: string
                example: '"profile-export-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"'
            X-Projection-Version:
              description: Shared versioned projection contract used by every requested profile result.
              schema:
                type: string
                example: de-energy-invoice-lines-csv:2.0.0
            Content-Disposition:
              description: Attachment filename generated by the selected batch projection.
              schema:
                type: string
                example: attachment; filename="german-energy-invoice-lines-2.csv"
            Cache-Control:
              description: Private no-store caching policy.
              schema:
                type: string
                example: private, no-store
          content:
            text/csv:
              schema:
                $ref: "#/components/schemas/GermanEnergyInvoiceLinesCsv"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: At least one requested ID is missing or outside the caller's account. No partial export or ownership detail is returned.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorEnvelope"
        "409":
          description: At least one extraction run is not finalized, at least one result fails the selected projection's batch-readiness policy, or the requested results do not share a compatible batch projection.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/ProfileExportNotReadyError"
                  - $ref: "#/components/schemas/ProfileExportIncompatibleError"
        "422":
          $ref: "#/components/responses/ValidationError"
        "429":
          $ref: "#/components/responses/RateLimited"
  /documents/{document}/extractions/reviews:
    post:
      summary: Review a profile result
      operationId: reviewDocumentExtraction
      description: Confirms or corrects one field, or rejects the complete profile result exposed under `sector_extraction`. For German energy full-invoice profile versions 2.0.0 and 2.0.1, confirmation and correction require `invoice_ref` so the decision changes only the selected `effective_payload.invoices[]` item; rejection applies to the complete packet and must omit `invoice_ref`. Decisions are append-only, idempotent, and guarded by the current extraction ETag. An accepted downstream handoff is terminal and rejects any later decision with `422`; consumers can therefore treat the first accepted handoff snapshot as final. The optional `review_duration_seconds` is caller-supplied workflow telemetry recording measured active human-review time spent reaching this individual decision; it is not processing wait time or wall-clock elapsed time. Omission or null leaves review-duration coverage incomplete and is not interpreted as zero. Both confirmation and correction require evidence supporting the complete reviewed value from a physical page owned by that invoice. Identifier evidence needs a type-compatible label in the evidence text; party and address corrections need the matching document role. Structured address components must be supported by the raw address and evidence, explicit country codes must be visible, and technical identifiers are format-checked in their canonical entity scope. Profile-specific field ownership rules are applied by the selected profile; for these German energy profiles, MaLo and legacy metering-point values belong to supply points, MeLo values to metering locations, meter numbers to meter assignments, and operator codes to operator objects. Manually submitted evidence text is a privileged reviewer attestation. exdata verifies the recorded component, physical page, and source but deliberately does not compare the transcription with OCR or native text, allowing authorized reviewers to correct OCR errors. Confirming or correcting a value does not clear an ambiguous supply-point association; affected relationship identifiers remain in review in the canonical payload until a new extraction resolves the association. API tokens require the `extractions:review` ability. A review-only token receives audit metadata after the write; add `documents:read` to receive field values and the full profile payload in this response.
      parameters:
        - $ref: "#/components/parameters/DocumentId"
        - $ref: "#/components/parameters/ReviewIdempotencyKey"
        - $ref: "#/components/parameters/IfMatch"
        - $ref: "#/components/parameters/RequestId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ProfileReviewDecisionRequest"
      responses:
        "201":
          description: Review decision recorded, or an identical decision replayed.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
            ETag:
              description: Updated profile-result entity tag.
              schema:
                type: string
                example: '"extraction-result-789-v1"'
            Idempotent-Replayed:
              description: Present with value `true` when an identical decision is replayed.
              schema:
                type: string
                enum: ["true"]
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ProfileReviewDecisionApplication"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: The profile result changed after it was read, or the idempotency key was reused with a different decision.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ProfileReviewConflictError"
        "422":
          description: The request is invalid, the result is rejected, or its accepted handoff is terminal and cannot receive another decision.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/ErrorEnvelope"
                  - type: object
                    properties:
                      errors:
                        type: object
                        additionalProperties:
                          type: array
                          items:
                            type: string
        "429":
          $ref: "#/components/responses/RateLimited"
  /previews/{preview}:
    get:
      summary: Download a preview file
      operationId: getPreview
      parameters:
        - name: preview
          in: path
          required: true
          x-client-variable: preview_id
          example: 987
          schema:
            type: integer
        - $ref: "#/components/parameters/RequestId"
      responses:
        "200":
          description: Preview file. The response content type follows the generated preview format.
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/RateLimitLimit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/RateLimitReset"
            X-RateLimit-Profile:
              $ref: "#/components/headers/RateLimitProfile"
            X-RateLimit-Scope:
              $ref: "#/components/headers/RateLimitScope"
            X-RateLimit-Window:
              $ref: "#/components/headers/RateLimitWindow"
          content:
            text/html:
              schema:
                type: string
                format: binary
            image/jpeg:
              schema:
                type: string
                format: binary
            image/png:
              schema:
                type: string
                format: binary
            image/gif:
              schema:
                type: string
                format: binary
            image/webp:
              schema:
                type: string
                format: binary
            application/pdf:
              schema:
                type: string
                format: binary
            application/octet-stream:
              schema:
                type: string
                format: binary
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/DocumentStorageUnavailable"
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API token
      description: Account-scoped API token created in the exdata app.
  headers:
    RateLimitLimit:
      description: Maximum number of requests allowed by the rate-limit policy reported for this response.
      schema:
        type: integer
        minimum: 1
        example: 300
    RateLimitRemaining:
      description: Number of requests remaining in the reported policy window.
      schema:
        type: integer
        minimum: 0
        example: 0
    RetryAfter:
      description: Number of seconds the client must wait before retrying the request.
      schema:
        type: integer
        minimum: 1
        example: 42
    RateLimitReset:
      description: Unix timestamp in seconds when the reported policy window resets.
      schema:
        type: integer
        format: int64
        minimum: 0
        example: 1785182400
    RateLimitProfile:
      description: Effective account quota profile. This header may be omitted for anonymous IP-scoped limits.
      schema:
        type: string
        enum: [restricted, standard, trusted, high_volume, enterprise]
        example: trusted
    RateLimitScope:
      description: Identity scope whose rate-limit policy is reported.
      schema:
        type: string
        enum: [token, account, user, ip]
        example: token
    RateLimitWindow:
      description: Time window used by the reported rate-limit policy.
      schema:
        type: string
        enum: [minute, hour, day]
        example: hour
  parameters:
    DocumentId:
      name: document
      in: path
      required: true
      x-client-variable: document_id
      example: 123
      schema:
        type: integer
      description: Document ID.
    ExtractionRunId:
      name: extractionRun
      in: path
      required: true
      x-client-variable: extraction_run_id
      example: 456
      schema:
        type: integer
        minimum: 1
      description: Extraction run ID. It must belong to the requested document and account.
    PhysicalPage:
      name: physicalPage
      in: path
      required: true
      x-client-variable: physical_page
      example: 1
      schema:
        type: integer
        minimum: 1
        maximum: 99999
      description: One-based physical page number cited by the exact profile extraction run.
    ProfileProjection:
      name: projection
      in: path
      required: true
      x-client-variable: projection
      schema:
        type: string
        minLength: 1
        maxLength: 120
        pattern: '^[A-Za-z0-9][A-Za-z0-9._-]{0,119}$'
        example: invoice-lines.csv
      description: Route segment of a projection registered by the profile. Read supported names and versions from the result's `exports` descriptors. German energy full-invoice profile versions 2.0.0 and 2.0.1 register `canonical.json` and `invoice-lines.csv`; only the CSV projection supports batch downloads.
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      schema:
        type: string
        maxLength: 255
      description: Optional unique key for safely retrying document uploads. After a temporary upload failure or gateway timeout, keep the same key, file, and form fields. Wait for Retry-After when provided. If no document was created, an identical retry can resume an interrupted upload; an active attempt can first return 409 with conflict_reason=processing. Reusing the same key with the same file and caller-supplied form fields, including processing mode, processing lane, and extraction profile, returns the stored response without duplicate processing or charges. Later changes to profile settings or prices do not alter that replay. Reusing a key with a different explicitly supplied mode or lane returns `409`, as does any other caller-supplied payload change. If an interrupted attempt created a document but could not finish the upload response, an identical retry returns `409 idempotency_conflict` with `conflict_reason=document_created` and the cleanup-only `document.id`; delete that document before deciding whether to submit a new upload.
    ReviewIdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      schema:
        type: string
        maxLength: 255
      description: 'Unique key for one logical extraction-review decision. An identical retry returns the original decision with `Idempotent-Replayed: true`; reuse with a different decision returns `409`.'
    IfMatch:
      name: If-Match
      in: header
      required: true
      schema:
        type: string
        pattern: '^"extraction-result-[0-9]+-v[0-9]+"$'
        example: '"extraction-result-789-v0"'
      description: ETag returned with a specialized profile result. A stale value returns `409 extraction_version_conflict`.
    PaymentSignature:
      name: PAYMENT-SIGNATURE
      in: header
      required: false
      schema:
        type: string
      description: Base64- or Base64URL-encoded x402 v2 PaymentPayload JSON. Omit this header to receive payment requirements in a 402 response.
    X402AccessToken:
      name: X-Access-Token
      in: header
      required: false
      schema:
        type: string
      description: Anonymous capability token returned by a successful x402 upload. Prefer this header when polling anonymous extraction status.
    X402AccessTokenQuery:
      name: access_token
      in: query
      required: false
      schema:
        type: string
      description: Anonymous capability token returned by a successful x402 upload. Header-based access is preferred when possible.
    RequestId:
      name: X-Request-ID
      in: header
      required: false
      schema:
        type: string
        maxLength: 128
      description: Optional caller-supplied request ID. exdata returns this value, or a generated ID, in the `X-Request-ID` response header and error body.
  responses:
    Forbidden:
      description: The token cannot access this resource.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorEnvelope"
    NotFound:
      description: Resource not found.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorEnvelope"
    RateLimited:
      description: Request rate limit exceeded.
      headers:
        X-RateLimit-Limit:
          $ref: "#/components/headers/RateLimitLimit"
        X-RateLimit-Remaining:
          $ref: "#/components/headers/RateLimitRemaining"
        Retry-After:
          $ref: "#/components/headers/RetryAfter"
        X-RateLimit-Reset:
          $ref: "#/components/headers/RateLimitReset"
        X-RateLimit-Profile:
          $ref: "#/components/headers/RateLimitProfile"
        X-RateLimit-Scope:
          $ref: "#/components/headers/RateLimitScope"
        X-RateLimit-Window:
          $ref: "#/components/headers/RateLimitWindow"
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/RateLimitError"
    UploadRateLimited:
      description: Request rate limit exceeded, or a test-mode token reached its daily sandbox upload limit.
      headers:
        X-RateLimit-Limit:
          $ref: "#/components/headers/RateLimitLimit"
        X-RateLimit-Remaining:
          $ref: "#/components/headers/RateLimitRemaining"
        Retry-After:
          $ref: "#/components/headers/RetryAfter"
        X-RateLimit-Reset:
          $ref: "#/components/headers/RateLimitReset"
        X-RateLimit-Profile:
          $ref: "#/components/headers/RateLimitProfile"
        X-RateLimit-Scope:
          $ref: "#/components/headers/RateLimitScope"
        X-RateLimit-Window:
          $ref: "#/components/headers/RateLimitWindow"
      content:
        application/json:
          schema:
            oneOf:
              - $ref: "#/components/schemas/RateLimitError"
              - $ref: "#/components/schemas/TestModeLimitError"
    ValidationError:
      description: Request validation failed.
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/ErrorEnvelope"
              - type: object
                properties:
                  errors:
                    type: object
                    additionalProperties:
                      type: array
                      items:
                        type: string
    IdempotencyConflict:
      description: The idempotency key is still processing, was reused with a different request payload such as a different processing mode or processing lane, or belongs to an interrupted attempt that created a document without completing the upload response. The last case returns `conflict_reason=document_created` with a cleanup-only `document.id`; delete that document before deciding whether to submit a new upload. A deletion response of `404` means the cleanup already completed.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/IdempotencyConflictError"
    DocumentStorageUnavailable:
      description: The requested file is temporarily unavailable. Wait for Retry-After before repeating this GET request. A temporary storage outage does not mean that the file was deleted.
      headers:
        Retry-After:
          $ref: "#/components/headers/RetryAfter"
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/ErrorEnvelope"
              - type: object
                required: [retry_after]
                properties:
                  retry_after:
                    type: integer
                    example: 60
          example:
            message: The service is temporarily unavailable. Please try again later.
            code: service_unavailable
            request_id: 926931a5-2e37-41cb-8ac9-fdd026ac402c
            retry_after: 60
    UploadUnavailable:
      description: The upload is temporarily unavailable. Wait for Retry-After, then retry with the same Idempotency-Key, file, and form fields. An interrupted upload that has not created a document can be retried without creating a duplicate document or charge. An active attempt may first return 409 with conflict_reason=processing; keep the same key while waiting.
      headers:
        Retry-After:
          description: Minimum delay in seconds before retrying the identical upload.
          schema:
            type: integer
            minimum: 1
            example: 60
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/ErrorEnvelope"
              - type: object
                required: [retry_after]
                properties:
                  code:
                    type: string
                    enum: [service_unavailable]
                  retry_after:
                    type: integer
                    minimum: 1
                    example: 60
  schemas:
    SupportedUploadFile:
      type: string
      format: binary
      x-supported-extensions:
        - pdf
        - doc
        - docx
        - jpg
        - jpeg
        - png
        - gif
        - tiff
        - tif
        - bmp
        - ico
        - psd
        - webp
        - heic
        - heif
        - mp4
        - m4v
        - mov
        - webm
        - ogv
        - ogg
        - html
        - txt
        - csv
        - json
        - edi
        - idoc
        - eml
        - msg
        - xml
      x-maximum-upload-kilobytes: 500000
      x-upload-limit:
        id: maximum_upload
        label: Maximum upload size
        value: 500000
        unit: kilobytes
        formatted: 500 MB
      x-live-capabilities-url: https://www.exdata.app/docs/api/files-and-versioning#supported-files
      x-live-capabilities-mcp-tool: get_extraction_schema
      x-file-capabilities:
        - id: pdf
          category: documents
          category_label: Documents
          family: documents
          family_label: Documents
          label: PDF
          extensions: [pdf]
          description: Invoices, credit notes, statements, letters, contracts, and exported reports.
          extraction: Extracts native text and uses bounded OCR for pages that need visual recovery before standard structured extraction.
          preview: Uses the first page for the thumbnail and creates a complete JPEG page set when the requested pages fit within the visual processing limits.
          limits:
            - id: pdf_ocr_pages
              label: Maximum PDF OCR pages
              unit: pages
              value_source: live_capabilities
            - id: pdf_render_pixels
              label: Maximum rendered PDF page area
              unit: pixels
              value_source: live_capabilities
            - id: pdf_rendered_file_bytes
              label: Maximum rendered PDF page file size
              unit: bytes
              value_source: live_capabilities
            - id: pdf_total_rendered_bytes
              label: Maximum rendered PDF data per document
              unit: bytes
              value_source: live_capabilities
            - id: pdf_ocr_text_bytes
              label: Maximum retained PDF OCR text per document
              unit: bytes
              value_source: live_capabilities
          notes:
            - Visual OCR and rendered previews are bounded by page, rendered-image, cumulative render-data, and recognized-text limits; native text extraction remains the primary path when available.
        - id: word
          category: documents
          category_label: Documents
          family: documents
          family_label: Documents
          label: Word
          extensions: [doc, docx]
          description: Word documents such as contracts, letters, statements, and reports.
          extraction: Converts the document to PDF, extracts native text when available, and uses OCR as a fallback before standard structured extraction.
          preview: Creates a PDF preview and a JPEG preview of the first page for the thumbnail.
          limits: []
          notes: []
        - id: jpeg
          category: images
          category_label: Images
          family: images
          family_label: Images
          label: JPEG
          extensions: [jpg, jpeg]
          description: Photographed documents, scanned pages, and image captures from mobile workflows.
          extraction: When AI processing is enabled and the file is within the visual AI input size limit, uses the source image as visual evidence for structured extraction. OCR text supports non-AI extraction, fallback, and cross-checking.
          preview: Normalizes the image to a JPEG preview and uses it for the thumbnail.
          limits:
            - id: ai_visual_input
              label: Maximum visual AI input size
              unit: bytes
              value_source: live_capabilities
          notes: []
        - id: png
          category: images
          category_label: Images
          family: images
          family_label: Images
          label: PNG
          extensions: [png]
          description: Scanned document pages, screenshots, and image-only uploads.
          extraction: When AI processing is enabled and the file is within the visual AI input size limit, uses the source image as visual evidence for structured extraction. OCR text supports non-AI extraction, fallback, and cross-checking.
          preview: Normalizes the image to a JPEG preview and uses it for the thumbnail.
          limits:
            - id: ai_visual_input
              label: Maximum visual AI input size
              unit: bytes
              value_source: live_capabilities
          notes: []
        - id: gif
          category: images
          category_label: Images
          family: images
          family_label: Images
          label: GIF
          extensions: [gif]
          description: GIF image uploads containing document content.
          extraction: Runs OCR on the rendered image before standard structured extraction.
          preview: Renders the image as a JPEG preview and uses it for the thumbnail.
          limits: []
          notes:
            - Animated content is not analyzed as a timeline.
        - id: tiff
          category: images
          category_label: Images
          family: images
          family_label: Images
          label: TIFF
          extensions: [tiff, tif]
          description: Single-page and multi-page scanned document images.
          extraction: Renders each page and runs OCR before standard structured extraction.
          preview: Creates a JPEG preview for every page and a combined PDF preview for multi-page files.
          limits: []
          notes: []
        - id: bmp
          category: images
          category_label: Images
          family: images
          family_label: Images
          label: BMP
          extensions: [bmp]
          description: Bitmap document scans and image exports.
          extraction: Runs OCR on the image before standard structured extraction.
          preview: Normalizes the image to a JPEG preview and uses it for the thumbnail.
          limits: []
          notes: []
        - id: ico
          category: images
          category_label: Images
          family: images
          family_label: Images
          label: ICO
          extensions: [ico]
          description: Icon image files containing text or document-like content.
          extraction: Runs OCR on the rendered image before standard structured extraction.
          preview: Renders the image as a JPEG preview and uses it for the thumbnail.
          limits: []
          notes: []
        - id: psd
          category: images
          category_label: Images
          family: images
          family_label: Images
          label: PSD
          extensions: [psd]
          description: Photoshop document images and flattened design exports.
          extraction: Runs OCR on the rendered image before standard structured extraction.
          preview: Renders the composite image as a JPEG preview and uses it for the thumbnail.
          limits: []
          notes:
            - Layers are not returned as separate documents.
        - id: webp
          category: images
          category_label: Images
          family: images
          family_label: Images
          label: WebP
          extensions: [webp]
          description: Web-native document images and browser-generated image exports.
          extraction: When AI processing is enabled and the file is within the visual AI input size limit, uses the source image as visual evidence for structured extraction. OCR text supports non-AI extraction, fallback, and cross-checking.
          preview: Normalizes the image to a JPEG preview and uses it for the thumbnail.
          limits:
            - id: ai_visual_input
              label: Maximum visual AI input size
              unit: bytes
              value_source: live_capabilities
          notes: []
        - id: heif
          category: images
          category_label: Images
          family: images
          family_label: Images
          label: HEIC and HEIF
          extensions: [heic, heif]
          description: High-efficiency photos and document captures from supported devices.
          extraction: Runs OCR on the rendered image before standard structured extraction.
          preview: Normalizes the image to a JPEG preview and uses it for the thumbnail.
          limits: []
          notes: []
        - id: mpeg-4-video
          category: video
          category_label: Video
          family: video
          family_label: Video
          label: MPEG-4 video
          extensions: [mp4, m4v]
          description: MPEG-4 video uploads, camera exports, and Apple-compatible video files.
          extraction: Extracts one representative frame, runs OCR on that frame, and uses it for standard structured extraction.
          preview: Creates one representative JPEG frame for the preview and thumbnail.
          limits:
            - id: video_decode_pixels
              label: Maximum decoded video frame
              value: 33177600
              unit: pixels
              formatted: 33,177,600 pixels (8K UHD)
              value_source: code_constant
          notes:
            - The container must include a decodable video stream. Audio is not transcribed and the full timeline is not analyzed.
        - id: quicktime-video
          category: video
          category_label: Video
          family: video
          family_label: Video
          label: QuickTime video
          extensions: [mov]
          description: QuickTime video files from cameras and editing workflows.
          extraction: Extracts one representative frame, runs OCR on that frame, and uses it for standard structured extraction.
          preview: Creates one representative JPEG frame for the preview and thumbnail.
          limits:
            - id: video_decode_pixels
              label: Maximum decoded video frame
              value: 33177600
              unit: pixels
              formatted: 33,177,600 pixels (8K UHD)
              value_source: code_constant
          notes:
            - The container must include a decodable video stream. Audio is not transcribed and the full timeline is not analyzed.
        - id: webm-video
          category: video
          category_label: Video
          family: video
          family_label: Video
          label: WebM video
          extensions: [webm]
          description: Web-native video files and browser recordings.
          extraction: Extracts one representative frame, runs OCR on that frame, and uses it for standard structured extraction.
          preview: Creates one representative JPEG frame for the preview and thumbnail.
          limits:
            - id: video_decode_pixels
              label: Maximum decoded video frame
              value: 33177600
              unit: pixels
              formatted: 33,177,600 pixels (8K UHD)
              value_source: code_constant
          notes:
            - The container must include a decodable video stream. Audio is not transcribed and the full timeline is not analyzed.
        - id: ogg-video
          category: video
          category_label: Video
          family: video
          family_label: Video
          label: Ogg video
          extensions: [ogv, ogg]
          description: Ogg container video files from open media workflows.
          extraction: Extracts one representative frame, runs OCR on that frame, and uses it for standard structured extraction.
          preview: Creates one representative JPEG frame for the preview and thumbnail.
          limits:
            - id: video_decode_pixels
              label: Maximum decoded video frame
              value: 33177600
              unit: pixels
              formatted: 33,177,600 pixels (8K UHD)
              value_source: code_constant
          notes:
            - The container must include a decodable video stream. Audio is not transcribed and the full timeline is not analyzed.
        - id: html
          category: text-and-data
          category_label: Text and structured data
          family: text-and-data
          family_label: Text and structured data
          label: HTML
          extensions: [html]
          description: Saved web documents, rendered invoice templates, and HTML exports.
          extraction: Reads the HTML source as document evidence before standard structured extraction.
          preview: Renders the uploaded markup as the page it describes and creates a JPEG screenshot for the thumbnail. The page is shown inert, keeping its own inline styles and data-URI images while scripts, embedded objects, and navigation never run. Link elements are removed and no external stylesheet, image, font, or other resource is loaded or connected to, so opening a preview stays invisible to whoever sent the document. A source above the rendering limit is shown as readable text up to the source text limit instead, and the preview says that it was truncated.
          limits:
            - id: preview_rendered_markup
              label: Maximum rendered markup preview
              value: 4194304
              unit: bytes
              formatted: 4 MiB
              value_source: code_constant
            - id: preview_source_text
              label: Maximum previewed source text
              value: 524288
              unit: bytes
              formatted: 512 KiB
              value_source: code_constant
          notes: []
        - id: plain-text
          category: text-and-data
          category_label: Text and structured data
          family: text-and-data
          family_label: Text and structured data
          label: Plain text
          extensions: [txt]
          description: Plain-text documents and text exported by upstream systems.
          extraction: Uses the source text directly as evidence for standard structured extraction.
          preview: Renders escaped source text to HTML and creates a JPEG screenshot for the thumbnail. Longer sources are shown up to the preview limit and the preview says that it was truncated.
          limits:
            - id: preview_source_text
              label: Maximum previewed source text
              value: 524288
              unit: bytes
              formatted: 512 KiB
              value_source: code_constant
          notes: []
        - id: csv
          category: text-and-data
          category_label: Text and structured data
          family: text-and-data
          family_label: Text and structured data
          label: CSV
          extensions: [csv]
          description: Tabular exports whose document data is already arranged in rows.
          extraction: Uses the source text directly as evidence for standard structured extraction.
          preview: Renders escaped source text to HTML and creates a JPEG screenshot for the thumbnail. Longer sources are shown up to the preview limit and the preview says that it was truncated.
          limits:
            - id: preview_source_text
              label: Maximum previewed source text
              value: 524288
              unit: bytes
              formatted: 512 KiB
              value_source: code_constant
          notes: []
        - id: json
          category: text-and-data
          category_label: Text and structured data
          family: text-and-data
          family_label: Text and structured data
          label: JSON
          extensions: [json]
          description: Structured source payloads to normalize into the standard extraction response.
          extraction: Uses the source text directly as evidence for standard structured extraction.
          preview: Renders escaped source text to HTML and creates a JPEG screenshot for the thumbnail. Longer sources are shown up to the preview limit and the preview says that it was truncated.
          limits:
            - id: preview_source_text
              label: Maximum previewed source text
              value: 524288
              unit: bytes
              formatted: 512 KiB
              value_source: code_constant
          notes: []
        - id: edi
          category: text-and-data
          category_label: Text and structured data
          family: text-and-data
          family_label: Text and structured data
          label: EDI
          extensions: [edi]
          description: Electronic data interchange payloads used in operations and procurement workflows.
          extraction: Uses the source text directly as evidence for standard structured extraction.
          preview: Renders escaped source text to HTML and creates a JPEG screenshot for the thumbnail. Longer sources are shown up to the preview limit and the preview says that it was truncated.
          limits:
            - id: preview_source_text
              label: Maximum previewed source text
              value: 524288
              unit: bytes
              formatted: 512 KiB
              value_source: code_constant
          notes: []
        - id: idoc
          category: text-and-data
          category_label: Text and structured data
          family: text-and-data
          family_label: Text and structured data
          label: IDoc
          extensions: [idoc]
          description: SAP IDoc exports and integration payloads.
          extraction: Uses the source text directly as evidence for standard structured extraction.
          preview: Renders escaped source text to HTML and creates a JPEG screenshot for the thumbnail. Longer sources are shown up to the preview limit and the preview says that it was truncated.
          limits:
            - id: preview_source_text
              label: Maximum previewed source text
              value: 524288
              unit: bytes
              formatted: 512 KiB
              value_source: code_constant
          notes: []
        - id: email-message
          category: email
          category_label: Email
          family: email
          family_label: Email
          label: Email message
          extensions: [eml, msg]
          description: RFC email and Outlook message files with envelope, body, and attachment evidence.
          extraction: Parses envelope fields and message text, then analyzes bounded PDF, XML, and common image attachment evidence when present.
          preview: Renders the readable text of the message body to HTML and creates a JPEG screenshot for the thumbnail. The message keeps its text, not its own styling, and previewable inline images follow the body. A longer body is shown up to the preview limit and the preview says that it was truncated.
          limits:
            - id: email_container
              label: Maximum email container size
              unit: bytes
              value_source: live_capabilities
            - id: email_attachment_count
              label: Maximum supported email attachments
              unit: attachments
              value_source: live_capabilities
            - id: email_individual_attachment
              label: Maximum individual email attachment size
              unit: bytes
              value_source: live_capabilities
            - id: email_total_attachments
              label: Maximum combined email attachment size
              unit: bytes
              value_source: live_capabilities
            - id: email_attachment_pdf_pages
              label: Maximum pages per attached PDF
              unit: pages
              value_source: live_capabilities
            - id: preview_email_body
              label: Maximum previewed message body
              value: 500000
              unit: bytes
              formatted: 488.3 KiB
              value_source: code_constant
          notes:
            - Email container and attachment processing are bounded by the current file limits.
        - id: xml
          category: xml-and-e-invoices
          category_label: XML and e-invoices
          family: xml-and-e-invoices
          family_label: XML and e-invoices
          label: XML and e-invoice XML
          extensions: [xml]
          description: CII, Factur-X/ZUGFeRD 2, the exact ZUGFeRD 1.0 COMFORT profile, XRechnung, UBL e-invoices, and generic XML exports.
          extraction: Uses deterministic schema, business-rule, and arithmetic validation plus document-level extraction for supported e-invoices. Standard XRechnung 3.0 UBL and CII and the exact Extension profile in UBL and CII syntax use their matching pinned KoSIT scenarios and report xml_profile_conformance. The exact CVD profile in CII syntax uses its matching pinned KoSIT scenario but reports structural_and_business; UBL CVD is not claimed as supported. The exact ZUGFeRD 1.0 COMFORT profile uses its bundled XSD and Schematron with pinned artifact checksums and reports structural_and_business. Generic XML is accepted but normally returns type other without standard document AI extraction.
          preview: Creates one human-readable HTML invoice visualization for every supported e-invoice in CII, UBL, and ZUGFeRD 1.0 COMFORT syntax, so the same invoice layout is returned regardless of the source format. Extension XRechnung 3.0 additionally keeps its source-ordered recursive invoice-line view. For exceptionally large line sets or repeatable review sections, the affected content is shown as a clearly labelled bounded prefix so browser rendering remains safe; the original XML remains unchanged. This HTML file is the canonical preview; the accompanying JPEG is only a representative thumbnail and visual fallback. Remaining safe XML is shown as pretty-printed XML. The visualization is labelled in the selected document locale.
          limits:
            - id: xml_source
              label: Maximum XML source size
              unit: bytes
              value_source: live_capabilities
            - id: xml_elements
              label: Maximum XML elements
              unit: elements
              value_source: live_capabilities
            - id: xml_depth
              label: Maximum XML nesting depth
              unit: levels
              value_source: live_capabilities
          notes:
            - Valid standard XRechnung 3.0 invoices in UBL and CII syntax, the exact Extension profile in UBL and CII syntax, the exact CVD profile in CII syntax, and the exact ZUGFeRD 1.0 COMFORT profile are supported. UBL CVD, ZUGFeRD 1.0 BASIC and EXTENDED, oversized, unsafe, or invalid invoices, and invoices with unknown or unsupported profiles fail closed instead of returning empty invoice data.
            - XML is admitted on element count and nesting depth as well as byte size, because a small source can still describe a disproportionately large document tree. A source past either bound is rejected before it is parsed, and reports structured_xml_complexity_limit.
            - Extension XRechnung 3.0 maps the document-level v1 fields. Recursive line hierarchy, embedded attachment metadata, and third-party payment rows feed the generated HTML visualization but are not returned as v1 extraction fields; exceptionally large line sets or repeatable review sections are shown as clearly labelled source-order prefixes. Multiple ambiguous payee accounts remain validation-only and leave the singular iban and bic fields null.
            - ZUGFeRD 1.0 COMFORT maps its validated document, party, payment, amount, tax, billing-period, and note values into the document-level v1 fields. The same support applies to authoritative XML embedded in a visibly matching PDF and to XML email attachments.
            - ZUGFeRD 1.0 COMFORT support is bounded to invoices with TypeCode 380 or 84 and the published tax TypeCodes VAT, ZF_INSURANCE_TAX (insurance tax), or AAJ (second-hand-parts tax); other document and tax codes fail closed.
            - For Extension XRechnung 3.0, gross_amount is the tax-inclusive invoice total (BT-112), not the remaining amount due after prepaid or third-party payment allocation.
            - For ZUGFeRD 1.0 COMFORT, gross_amount is GrandTotalAmount; the optional DuePayableAmount is validation and linkage evidence, not the extracted gross total.
            - CVD XRechnung 0.9 CII and ZUGFeRD 1.0 COMFORT remain supported and fully execute their stated validators, but report structural_and_business without claiming complete XML profile conformance.
      description: >
        Supported extensions are PDF, DOC, DOCX, JPG, JPEG, PNG, GIF, TIFF,
        TIF, BMP, ICO, PSD, WebP, HEIC, HEIF, MP4, M4V, MOV, WebM, OGV, OGG,
        HTML, TXT, CSV, JSON, EDI, IDoc, EML, MSG, and XML. Files can be up to
        500 MB. XML source, email container and attachment, and PDF visual OCR
        limits can vary by file type. Retrieve their current values from the
        live supported-files documentation or the MCP get_extraction_schema
        tool. Videos use one representative decoded frame; exdata does not
        transcribe audio or analyze the full video. Video containers must
        include a decodable video stream, and decoded frames must not exceed
        33177600 pixels; audio-only files and oversized video frames fail during
        processing.
    ErrorEnvelope:
      type: object
      required: [message, code, request_id]
      properties:
        message:
          type: string
        code:
          type: string
          example: validation_failed
        request_id:
          type: string
          example: req_01HZY9Z4Z6E7B3F42X8E8Y9ABC
    IdempotencyConflictError:
      oneOf:
        - $ref: "#/components/schemas/IdempotencyPendingOrPayloadConflictError"
        - $ref: "#/components/schemas/IdempotencyDocumentCreatedConflictError"
    IdempotencyPendingOrPayloadConflictError:
      allOf:
        - $ref: "#/components/schemas/ErrorEnvelope"
        - type: object
          required: [conflict_reason]
          properties:
            code:
              type: string
              enum: [idempotency_conflict]
            conflict_reason:
              type: string
              enum: [processing, payload_mismatch]
    IdempotencyDocumentCreatedConflictError:
      allOf:
        - $ref: "#/components/schemas/ErrorEnvelope"
        - type: object
          required: [conflict_reason, document]
          properties:
            code:
              type: string
              enum: [idempotency_conflict]
            conflict_reason:
              type: string
              enum: [document_created]
            document:
              type: object
              required: [id]
              properties:
                id:
                  type: integer
                  minimum: 1
                  description: Cleanup-only identifier for the document created by the interrupted upload.
    RateLimitError:
      allOf:
        - $ref: "#/components/schemas/ErrorEnvelope"
        - type: object
          required: [retry_after]
          properties:
            rate_limit_profile:
              type: string
              enum: [restricted, standard, trusted, high_volume, enterprise]
              description: Effective account quota profile. Omitted for anonymous IP-scoped limits.
              example: trusted
            rate_limit_scope:
              type: string
              enum: [token, account, user, ip]
              description: Identity scope of the policy that rejected the request.
              example: token
            rate_limit_window:
              type: string
              enum: [minute, hour, day]
              description: Time window of the policy that rejected the request.
              example: hour
            rate_limit_limit:
              type: integer
              minimum: 1
              description: Maximum requests allowed by the policy that rejected the request.
              example: 300
            retry_after:
              type: integer
              minimum: 1
              description: Number of seconds to wait before retrying. This matches the `Retry-After` response header.
              example: 42
    PaginatedDocuments:
      type: object
      required: [data, links, meta]
      properties:
        data:
          type: array
          items:
            $ref: "#/components/schemas/Document"
        links:
          type: object
        meta:
          type: object
    DocumentResource:
      type: object
      required: [data]
      properties:
        data:
          $ref: "#/components/schemas/Document"
    X402ExtractionAccepted:
      type: object
      required: [data, anonymous_access, payment]
      properties:
        data:
          $ref: "#/components/schemas/Document"
        anonymous_access:
          type: object
          required: [status_url, expires_at, token_header]
          properties:
            status_url:
              type: string
              format: uri
              description: Anonymous polling URL for this extraction. Send the returned access token in the `X-Access-Token` header when polling. Query-string tokens are also accepted, but generated URLs do not embed them.
            access_token:
              type: string
              description: Capability token returned on upload and replay responses. Use it as `X-Access-Token` when polling.
            expires_at:
              type: string
              format: date-time
              nullable: true
            token_header:
              type: string
              example: X-Access-Token
        payment:
          $ref: "#/components/schemas/X402PaymentSummary"
    X402PaymentSummary:
      type: object
      properties:
        scheme:
          type: string
          example: exact
        network:
          type: string
          example: eip155:8453
        asset:
          type: string
          example: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
        amount:
          type: string
          example: "150000"
        pay_to:
          type: string
          nullable: true
        payer:
          type: string
          nullable: true
        transaction:
          type: string
          nullable: true
    X402PaymentError:
      allOf:
        - $ref: "#/components/schemas/ErrorEnvelope"
        - type: object
          required: [x402]
          properties:
            x402:
              $ref: "#/components/schemas/X402PaymentRequired"
            verification:
              type: object
              nullable: true
            settlement:
              type: object
              nullable: true
    X402PaymentRequired:
      type: object
      required: [x402Version, resource, accepts]
      properties:
        x402Version:
          type: integer
          enum: [2]
        error:
          type: string
          nullable: true
        resource:
          type: object
          required: [url, description, mimeType]
          properties:
            url:
              type: string
              format: uri
            description:
              type: string
            mimeType:
              type: string
              example: application/json
        accepts:
          type: array
          items:
            $ref: "#/components/schemas/X402PaymentRequirement"
        extensions:
          type: object
          additionalProperties: true
    X402PaymentRequirement:
      type: object
      required: [scheme, network, asset, amount, payTo]
      properties:
        scheme:
          type: string
          example: exact
        network:
          type: string
          description: CAIP-2 network identifier.
          example: eip155:8453
        asset:
          type: string
          description: Token contract or network-specific asset identifier.
          example: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
        amount:
          type: string
          description: Atomic token amount required by the x402 exact payment scheme.
          example: "150000"
        payTo:
          type: string
          description: Merchant wallet address.
        maxTimeoutSeconds:
          type: integer
          example: 60
        extra:
          type: object
          additionalProperties: true
    Document:
      type: object
      properties:
        id:
          type: integer
        mode:
          type: string
          enum: [live, test]
          description: Token environment that created the document. Test documents are created by test-mode API tokens and have zero live credit usage. Live extraction-, analysis-, and validation-mode documents use result-based page-band billing and keep the final total when a usable result or retrievable extracted fields remain; live thumbnail-only documents have zero credit usage.
        processing_mode:
          type: string
          enum: [extraction, analysis, validation, thumbnail]
          default: extraction
          description: Processing selected at upload. `extraction` is the default and live runs keep the profile `credit_cost` recorded for each started 10-page band when a usable result or retrievable extracted fields remain; generic extraction has a rate of one. `analysis` runs the same lifecycle and generic billing without the AI step and without structured extraction. `validation` accepts PDF or XML and returns only the structured-invoice assessment in the extraction-run quality object, without AI, general extraction, persisted previews, a thumbnail, or retained document text. Both report `ai_processing=false`. `thumbnail` generates only the JPEG thumbnail and has no extraction run, extraction results, persisted previews, OCR or extracted text, AI processing, or credit charge.
        processing_lane:
          type: string
          enum: [standard, batch]
          default: standard
          description: Processing priority selected at upload. `standard` is the default lane. `batch` is available to eligible accounts and is returned when selected for the upload; it uses lower-priority constrained capacity and can have longer processing waits without changing result fields, polling, statuses, or lifecycle webhooks. If batch is unavailable for the account, the upload returns `422` with `code=validation_failed` and a `processing_lane` validation error.
        pages:
          type: string
          nullable: true
          description: Normalized page selection stored for this upload, exactly as requested, such as `first,last` or `all`. `null` when the upload did not send a selection; selections only exist in analysis mode.
        status:
          type: string
          enum: [pending, completed, error, blocked]
        processing_stage:
          type: string
          nullable: true
          enum: [queued, waiting_for_auto_top_up, waiting_for_capacity, thumbnailing, analyzing, extracting, completed, failed, blocked_insufficient_credits]
          description: Current processing lifecycle stage. Thumbnail-only documents progress through `queued`, `thumbnailing`, and `completed`, or `failed` on error, and can also report `waiting_for_capacity` because thumbnail rendering uses standard processing capacity. `waiting_for_auto_top_up` applies to extraction, analysis, and validation and means processing is paused while a pending automatic credit top-up completes. `waiting_for_capacity` means the document was accepted while your account already has the maximum number of standard-lane documents processing at once; it starts automatically as your earlier documents finish, and no action is required. Batch-lane documents are never held this way. After a successful `201`, page-band calculation can still move a run to `blocked_insufficient_credits` with `blocked_reason=page_band_insufficient_credits` if available credits do not cover an additional 10-page band.
          example: queued
        processing_error:
          type: string
          nullable: true
        blocked_reason:
          type: string
          nullable: true
          example: insufficient_credits
        scanner_status:
          type: string
          nullable: true
          enum: [clean, rejected]
        scanner_provider:
          type: string
          nullable: true
          description: Label identifying the scanner result source when available.
          example: default
        scanner_message:
          type: string
          nullable: true
        scanned_at:
          type: string
          format: date-time
          nullable: true
        processing_started_at:
          type: string
          format: date-time
          nullable: true
        processed_at:
          type: string
          format: date-time
          nullable: true
        filename:
          type: string
          example: invoice.pdf
        file_format:
          type: string
          example: pdf
        file_size:
          type: integer
          example: 240123
        additional_text:
          type: string
          nullable: true
        additional_text_plain:
          type: string
          nullable: true
        custom_types:
          type: array
          nullable: true
          items:
            type: string
        requester:
          type: string
          nullable: true
          maxLength: 255
          description: Caller-supplied upload metadata. For `de.energy.supply-invoice`, it does not affect profile extraction.
        locale:
          type: string
          nullable: true
          enum: [en, de, fr, es, it, pl, nl, pt, ro]
          example: en
          description: Selected document language used for extraction and localized previews.
        number_of_pages:
          type: integer
          nullable: true
        extracted_text:
          type: string
          nullable: true
          description: "Text read from the document exactly as extraction produced it. It retains page boundaries as form feed characters and keeps bracketed diagnostic and structure markers, such as `[PAGE OCR WARNING: OCR RETURNED NO TEXT]` or the email section delimiters, that record how the text was produced. Use this field when you need that provenance."
        extracted_text_plain:
          type: string
          nullable: true
          description: The same text normalized for reading and indexing. Whitespace is collapsed, diagnostic and email structure markers are removed, and page boundaries remain as form feed characters, which every tokenizer treats as whitespace. Prefer this field for full-text search and display, and split on the form feed when you need per-page text.
        origin:
          type: string
          nullable: true
          enum: [api, app, mcp, x402]
        ai_processing:
          type: boolean
          description: Whether AI extraction is enabled for this document. This is always `false` in thumbnail, analysis, and validation mode. In extraction mode, `allow_ai_processing=false` makes it false without disabling OCR, previews, non-AI structured extraction, or page-band credit calculation.
        extraction_profile:
          type: string
          example: de.energy.supply-invoice
          x-extensible-enum: [generic, de.energy.supply-invoice]
          description: Effective extraction profile selected when the document was uploaded. Omitted profile selection resolves to `generic`; an explicitly selected registered profile is available to every active account. The effective profile version is recorded for the run. Profile setting changes apply to new uploads only.
        is_e_invoice:
          type: boolean
          description: True only when a supported structured e-invoice was accepted after validation. Recognition of invoice-like XML alone does not set this flag.
        thumbnail:
          type: string
          format: uri
          nullable: true
          description: Download URL for the generated JPEG thumbnail. Video thumbnails contain a representative decoded frame.
        previews:
          type: array
          nullable: true
          description: Persisted preview files when loaded. Thumbnail-only documents have no preview rows; the preview-list endpoint returns an empty array after completion.
          items:
            $ref: "#/components/schemas/Preview"
        extractions:
          description: Structured extraction results when loaded. Structured extraction does not run in thumbnail, analysis, or validation mode; completed documents in those modes return an empty array.
          oneOf:
            - $ref: "#/components/schemas/NullableExtractions"
            - type: array
              maxItems: 0
              description: Empty array returned for a completed thumbnail-only, analysis, or validation document.
        latest_extraction_run:
          $ref: "#/components/schemas/ExtractionRun"
        sector_extraction_summary:
          oneOf:
            - $ref: "#/components/schemas/SectorExtractionSummary"
            - $ref: "#/components/schemas/ProfileNullValue"
          description: Compact state of the effective specialized profile result under `sector_extraction_summary`. The newest usable result takes precedence over later failed retries; when every attempt failed, the latest failure is effective. Null for generic documents and profile documents without a stored result.
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    ExtractionRun:
      type: object
      nullable: true
      description: Latest extraction attempt metadata. Null for thumbnail-only documents because no extraction run is created. Reprocessing an existing document preserves the profile version, processing settings, and credit rate recorded for that document. Profile setting changes apply to new uploads only.
      properties:
        id:
          type: integer
        mode:
          type: string
          enum: [live, test]
        processing_lane:
          type: string
          enum: [standard, batch]
          default: standard
          description: Processing priority used for this extraction attempt. It matches the document processing lane.
        source:
          type: string
          nullable: true
          enum: [api, app, mcp, x402]
        status:
          type: string
          enum: [pending, processing, completed, blocked, error]
        blocked_reason:
          type: string
          nullable: true
          example: insufficient_credits
        error_code:
          type: string
          nullable: true
          description: Machine-readable failure category. `unsupported_structured_invoice` means extraction-mode XML was deterministically rejected because it exceeded safety limits, was unsafe or malformed, violated structured-invoice validation rules, or used an unsupported profile. Standard XRechnung 3.0 and the exact Extension profile in supported UBL and CII syntax report `xml_profile_conformance`. The exact CVD profile in CII syntax and ZUGFeRD 1.0 COMFORT remain supported but report `structural_and_business`; UBL CVD is not claimed as supported. Inspect `quality.structured.validation_status`, `assessment`, and `validation_errors`, then correct the XML or convert it to a supported profile before resubmitting it. Technical validator unavailability is retryable and is never classified as an invalid invoice.
        error_message:
          type: string
          nullable: true
        credits_charged:
          type: integer
          nullable: true
          minimum: 0
          description: Current net billable units attributed to this extraction run. A live run starts with one profile-rate band, calculates usage after analysis as `credit_cost × started 10-page bands`, and keeps that total when a usable result or retrievable extracted fields remain. It becomes zero when credits are returned after a terminal error that leaves neither, or after a page-band availability block. Test and other non-credit runs report zero. Reprocessing after an already completed usable result also reports zero; reprocessing after a fully returned failure reports its new page-band charge when it first leaves a usable result or retrievable extracted fields. Null means no credit usage was recorded, such as an initial insufficient-credit block or a run waiting for automatic top-up.
          example: 2
        extraction_schema_version:
          type: string
          nullable: true
          example: "2026-08-28.1"
        extractor_version:
          type: string
          nullable: true
          example: document:2026-09-05.1
        ai_prompt_version:
          type: string
          nullable: true
          example: document-ai:2026-09-05.1
        normalization_version:
          type: string
          nullable: true
          example: base:2026-11-15.1
        extraction_profile:
          type: string
          example: de.energy.supply-invoice
          x-extensible-enum: [generic, de.energy.supply-invoice]
        profile_version:
          type: string
          nullable: true
          example: "2.0.1"
        ai_model:
          type: string
          nullable: true
          description: Processing model recorded for this extraction run.
          example: gpt-5.4-mini-2026-03-17
        ai_reasoning_effort:
          type: string
          nullable: true
          maxLength: 30
          description: Reasoning setting recorded for this extraction run. Null when the run does not use one.
          example: low
        strategies_used:
          type: array
          nullable: true
          items:
            type: string
          example: [page_manifest, structured_output, deterministic_validation]
        provenance_summary:
          type: object
          nullable: true
          additionalProperties: false
          description: Summary of the winning value provenance for non-null extraction fields in this run. Null when no automatic winning-field provenance snapshot was persisted, including legacy, in-progress, analysis, validation, and reviewed-profile runs; this is separate from the broader processing strategies in `strategies_used`.
          required: [classification, methods_used, field_counts]
          properties:
            classification:
              type: string
              enum: [none, structured_invoice, ai, deterministic, structured_markup, email_envelope, derived, unknown, mixed]
            methods_used:
              type: array
              uniqueItems: true
              items:
                type: string
                enum: [structured_invoice, ai, deterministic, structured_markup, email_envelope, derived, unknown]
            field_counts:
              type: object
              additionalProperties: false
              description: Number of selected non-null fields attributed to each method that appears in `methods_used`.
              properties:
                structured_invoice:
                  type: integer
                  minimum: 1
                ai:
                  type: integer
                  minimum: 1
                deterministic:
                  type: integer
                  minimum: 1
                structured_markup:
                  type: integer
                  minimum: 1
                email_envelope:
                  type: integer
                  minimum: 1
                derived:
                  type: integer
                  minimum: 1
                unknown:
                  type: integer
                  minimum: 1
        billing_mode:
          type: string
          description: Billing treatment recorded for the run. This is informational run metadata, not an upload parameter; use `credit_cost` for billing calculations rather than branching on this label.
        credit_cost:
          type: integer
          minimum: 0
          maximum: 100
          description: Credits per started 10-page band recorded for this run. Multiply this rate by the number of started bands to obtain the final billable total kept when a usable result or retrievable extracted fields remain. A zero value indicates that no credits are charged for the run. Profile setting changes apply to new uploads only, while reprocessing an existing document preserves the rate recorded for that document.
          example: 3
        credit_cost_source:
          type: string
          description: Indicates how the recorded per-band rate was determined. This is returned run metadata, not an upload parameter; treat the value as extensible and use `credit_cost` as the applicable rate.
        quality:
          $ref: "#/components/schemas/ExtractionQuality"
        started_at:
          type: string
          format: date-time
          nullable: true
        completed_at:
          type: string
          format: date-time
          nullable: true
        created_at:
          type: string
          format: date-time
    ExtractionQuality:
      type: object
      nullable: true
      description: >
        Extraction quality and degradation information. Null for older or
        not-yet-evaluated runs and when no AI, PDF, email-attachment, or
        structured-invoice quality
        metadata applies, including completed deterministic and AI-disabled
        runs without applicable PDF, email, or structured-source signals. This status summarizes
        detected processing degradation only; it is not a confidence score or
        an accuracy guarantee. `normal` means that no unresolved degradation
        remains after bounded recovery.
      required: [status, degraded, reasons, ai, pdf, email, structured]
      properties:
        status:
          type: string
          enum: [normal, degraded]
          description: >
            Processing-path status. `normal` means no unresolved degradation
            remains after bounded recovery, not that every extracted value is
            correct.
        degraded:
          type: boolean
        reasons:
          type: array
          items:
            type: string
          description: Stable machine-readable reasons why the result needs additional review.
        ai:
          $ref: "#/components/schemas/ExtractionAiQuality"
        pdf:
          $ref: "#/components/schemas/ExtractionPdfQuality"
        email:
          $ref: "#/components/schemas/ExtractionEmailQuality"
        structured:
          $ref: "#/components/schemas/ExtractionStructuredQuality"
    ExtractionAiQuality:
      type: object
      nullable: true
      required:
        - status
        - model
        - reasoning_effort
        - service_tier
        - max_output_tokens
        - input_mode
        - text_purpose
        - detail
        - preflight_unavailable
        - low_detail_document_text_cross_checked
        - document_text_truncated
        - email_text_truncated
        - deterministic_supplementation
        - no_usable_text
        - conflict_fields
        - rejected_fields
        - recovered_fields
      properties:
        status:
          type: string
          nullable: true
        model:
          type: string
          nullable: true
          description: Requested processing model. Null for older runs.
        reasoning_effort:
          type: string
          nullable: true
          description: Requested reasoning setting. Null for older runs or models without this setting.
        service_tier:
          type: string
          nullable: true
          description: Requested service tier. Null for older runs.
        max_output_tokens:
          type: integer
          minimum: 1
          nullable: true
          description: Requested maximum output-token budget. Null for older runs.
        input_mode:
          type: string
          nullable: true
          enum: [attachment, text, attachment+text]
          description: >
            Evidence modes that contributed to the final result across one or
            more extraction attempts. `attachment+text` represents separately
            evaluated attachment and local-text evidence; the same PDF or
            supported source-image content is not sent twice in one request.
        text_purpose:
          type: string
          nullable: true
          enum: [operational_fallback, document_cross_check]
          description: >
            Why a text-only model pass contributed. `operational_fallback`
            preserves bounded document and email context when attachment input
            cannot be used or repairs incomplete or partially valid attachment
            evidence. A complete, untruncated, document-only fallback can leave
            quality `normal` only when it recovers a narrowly supported field
            from clean high-detail PDF processing, the recovered value is
            deterministically corroborated by document text, and no other text
            field contributes. The current recovery is limited to a
            one-character correction of a checksum-only IBAN rejection when
            the corrected value is the sole distinct valid IBAN in the
            document. `document_cross_check` is an independent, document-only
            verification of low-detail PDF or supported source-image evidence.
            Null when text did not contribute or for older runs.
        detail:
          type: string
          nullable: true
          enum: [high, low]
          description: >
            Visual detail used for final PDF page-image or supported
            source-image attachment evidence. It does not remove text extracted
            locally from the document. High detail is the primary path. Low
            detail reduces image processing as a context-limit fallback and is
            cross-checked for detected conflicts against independently extracted
            document or OCR text when that text is available.
        preflight_unavailable:
          type: boolean
          description: >
            True when exact input-size measurement was unavailable.
            The extraction is marked degraded and uses a conservative
            low-detail or bounded-text path instead of silently sending
            unmeasured high-detail attachment input.
        low_detail_document_text_cross_checked:
          type: boolean
          nullable: true
          description: >
            True when a low-detail PDF or supported source-image result was
            compared with a separate model pass over locally extracted
            document or OCR text without supplemental email evidence. False
            when the final attachment detail was low but no successful
            document-only cross-check contributed, or
            when document and email evidence shared the fallback pass and
            field-level provenance could not be isolated. Null when not
            applicable or unavailable on an older run. Supplemental email text
            alone does not count.
        document_text_truncated:
          type: boolean
        email_text_truncated:
          type: boolean
        deterministic_supplementation:
          type: boolean
        no_usable_text:
          type: boolean
          description: True when neither an attachment nor extracted text could be supplied to AI extraction.
        conflict_fields:
          type: array
          items:
            type: string
        rejected_fields:
          type: array
          items:
            type: string
          description: Unresolved fields discarded because they failed deterministic semantic validation.
        recovered_fields:
          type: array
          items:
            type: string
          description: >
            Fields that initially failed deterministic semantic validation but
            were safely recovered from independently evaluated, corroborated
            document text. A normal recovery currently requires a
            one-character correction of a checksum-only IBAN rejection and the
            corrected value must be the sole distinct valid IBAN in the
            document. This provenance can be present when overall quality is
            normal.
    ExtractionPdfQuality:
      type: object
      nullable: true
      required:
        - page_count
        - page_count_known
        - native_text_available
        - native_text_truncated
        - ocr_attempted_pages
        - ocr_successful_pages
        - ocr_page_limit_reached
        - ocr_page_limit
        - pages_beyond_ocr_limit
        - failed_pages
        - skipped_pages
        - empty_pages
        - blank_pages
        - conflict_pages
        - unreliable_pages
        - limited_pages
      properties:
        page_count:
          type: integer
          nullable: true
          minimum: 0
          description: Exact total when page_count_known is true; otherwise the number of pages confirmed before bounded discovery stopped.
        page_count_known:
          type: boolean
          nullable: true
        native_text_available:
          type: boolean
        native_text_truncated:
          type: boolean
        ocr_attempted_pages:
          type: integer
          minimum: 0
        ocr_successful_pages:
          type: integer
          minimum: 0
        ocr_page_limit_reached:
          type: boolean
          description: True when bounded page discovery could not safely determine the remaining coverage, or when at least one selected page beyond the OCR budget still required visual OCR. A document can have reliable native-text pages beyond the budget while this remains false.
        ocr_page_limit:
          type: integer
          nullable: true
          minimum: 1
        pages_beyond_ocr_limit:
          type: integer
          nullable: true
          minimum: 0
          description: Number of selected pages beyond the OCR page budget that bounded native-text and embedded-image checks determined still required visual OCR. Reliable native-text tail pages are not counted. Null when the page probe found more pages but could not determine the total safely.
        failed_pages:
          type: array
          items:
            type: integer
            minimum: 1
        skipped_pages:
          type: array
          items:
            type: integer
            minimum: 1
        empty_pages:
          type: array
          items:
            type: integer
            minimum: 1
          description: Pages selected for OCR whose rendered content was not confirmed blank but produced no OCR text; these are degradation signals.
        blank_pages:
          type: array
          items:
            type: integer
            minimum: 1
          description: Pages conservatively confirmed visually blank before OCR. They are retained in the page count, skipped by OCR, and do not by themselves degrade the result.
        conflict_pages:
          type: array
          items:
            type: integer
            minimum: 1
        unreliable_pages:
          type: array
          items:
            type: integer
            minimum: 1
        limited_pages:
          type: array
          items:
            type: integer
            minimum: 1
    ExtractionEmailQuality:
      type: object
      nullable: true
      description: >
        Bounded EML/MSG parsing and attachment-selection provenance. Exdata
        selects one primary financial attachment for the single extraction
        result. A supported e-invoice XML has priority only after structural
        and arithmetic validation and, when a PDF representation accompanies
        it, source linkage without critical-field conflicts. The linked XML
        and PDF are treated as paired representations of one invoice.
        Otherwise the first usable PDF, non-inline image, or inline image is
        selected in priority order. Failed or rejected candidates can be
        bypassed in favor of the next usable candidate. Unsupported explicit
        attachments, parser fallbacks, failed analysis, evidence truncation,
        and multiple document candidates are review signals.
      required:
        - attachments_seen
        - supported_attachments
        - processed_attachments
        - ignored_attachments
        - skipped_attachments
        - failed_attachments
        - skipped_reasons
        - failed_reasons
        - evidence_truncated
        - body_truncated
        - parse_fallback
        - parse_failed
        - multiple_document_attachments
      properties:
        attachments_seen:
          type: integer
          minimum: 0
        supported_attachments:
          type: integer
          minimum: 0
          description: Attachments recognized by bounded content inspection, independent of declared filename or MIME type.
        processed_attachments:
          type: integer
          minimum: 0
          maximum: 1
          description: Attachments that contributed substantive local text or structured evidence to the single extraction result.
        ignored_attachments:
          type: integer
          minimum: 0
          description: Inline or clearly decorative content that was intentionally ignored.
        skipped_attachments:
          type: integer
          minimum: 0
          description: Explicit attachments not selected or not processed because of a safety or format limit.
        failed_attachments:
          type: integer
          minimum: 0
          description: Candidate attachments whose bounded validation or local analysis failed.
        skipped_reasons:
          type: array
          items:
            type: string
        failed_reasons:
          type: array
          items:
            type: string
        evidence_truncated:
          type: boolean
        body_truncated:
          type: boolean
          description: True when the parsed email body was bounded before extraction.
        parse_fallback:
          type: boolean
          description: True when an otherwise empty EML parse used bounded raw EML text as a degraded fallback.
        parse_failed:
          type: boolean
          description: True when the email parser failed. MSG parser failures fail the processing stage closed.
        multiple_document_attachments:
          type: boolean
          description: >
            True when more than one non-decorative document candidate was
            present. Only one primary attachment contributes to the result;
            review this signal before automating critical values.
    XmlInvoiceValidation:
      type: object
      additionalProperties: false
      description: >
        XML validation only, independent of PDF/text linkage and extraction
        authority. Use this result and its findings for an XML-validity indicator.
        A passing XML result does not assert that the visible PDF matches or
        that extracted metadata is correct. Older snapshots may omit this object;
        absence means no separately recorded XML result.
      required: [contract_version, detection_status, validation_status, validation_scope, assessment, validator, finding_counts, findings, findings_truncated, validation_errors, validation_rule_ids]
      properties:
        contract_version:
          type: integer
          enum: [1]
        detection_status:
          $ref: '#/components/schemas/ExtractionStructuredQuality/properties/detection_status'
        validation_status:
          type: string
          enum: [not_applicable, valid, valid_with_warnings, invalid, unsupported, unavailable, not_evaluable]
          description: Outcome of the XML checks in validation_scope. PDF/text conflicts and OCR availability do not change this value.
        validation_scope:
          $ref: '#/components/schemas/ExtractionStructuredQuality/properties/validation_scope'
        assessment:
          type: string
          enum: [pass, pass_with_warnings, fail, indeterminate, not_applicable]
          description: XML-only outcome. Does not incorporate source linkage or extraction authority.
        validator:
          $ref: '#/components/schemas/ExtractionStructuredQuality/properties/validator'
        finding_counts:
          $ref: '#/components/schemas/ExtractionStructuredQuality/properties/finding_counts'
        findings:
          $ref: '#/components/schemas/ExtractionStructuredQuality/properties/findings'
        findings_truncated:
          $ref: '#/components/schemas/ExtractionStructuredQuality/properties/findings_truncated'
        validation_errors:
          type: array
          items:
            type: string
          description: XML-validation reason codes only. Source-linkage and OCR reasons belong to the enclosing structured result.
        validation_rule_ids:
          $ref: '#/components/schemas/ExtractionStructuredQuality/properties/validation_rule_ids'
    ExtractionStructuredQuality:
      type: object
      nullable: true
      description: >
        Versioned validation and source-linkage provenance for CII,
        Factur-X/ZUGFeRD, XRechnung, and supported UBL invoices. New snapshots
        include `contract_version`, explicit detection and validation states,
        an objective `assessment`, the independent `xml_validation` result, the exact validation scope, and bounded
        document-data-free findings. Older stored snapshots can omit those new
        fields; their absence is unknown rather than proof that no e-invoice
        was detected. A structured payload becomes authoritative only when its
        syntax and profile are supported, the stated structural and business
        checks pass, and any paired human-readable PDF representation is
        linked without critical-field conflicts. XML profile conformance,
        PDF/XML linkage, and PDF/A or container conformance are separate
        concerns; this object does not claim legal validity or complete PDF/A
        container validation. Rejected structured values are not silently used.
        Credit-note numbers identify the current document; references to an
        original invoice do not establish its identity or document type.
        German document-number labels (Belegnummer, Beleg-Nr.) identify the
        current document when supported by other matching invoice evidence;
        these labels alone do not establish whether it is an invoice or credit note.
        Customer-number and page headings do not count as document numbers;
        values under another field heading do not establish document identity.
        Recognized invoice headers can also establish linkage when labels and
        values appear in separate ordered columns. The field order must be
        complete and unambiguous; customer, contract, and page values are not
        invoice identifiers. This also applies to complete header rows that
        include customer, contract, or page columns. Separately listed net,
        tax, gross, and payable labels are associated with their amounts only
        when both columns are complete and unambiguous on the same page.
        Ambiguous total rows with several amounts and no separate field labels
        do not establish a critical-field conflict.
      required:
        - source
        - syntax
        - profile_identifier
        - profile_name
        - recognized_invoice
        - within_size_limit
        - well_formed
        - safe_xml
        - parser_supported
        - schema_valid
        - schema_violation_count
        - business_rules_valid
        - authority
        - linkage_checked
        - linkage_source
        - linked
        - validation_errors
        - validation_rule_ids
        - matched_fields
        - conflict_fields
        - unverified_fields
      properties:
        xml_validation:
          $ref: '#/components/schemas/XmlInvoiceValidation'
        contract_version:
          type: integer
          enum: [1]
          description: Present on structured-quality snapshots written with the versioned assessment contract. Its absence identifies a legacy or otherwise unversioned snapshot.
        detection_status:
          type: string
          enum: [recognized, not_detected, inconclusive]
          description: Result of the structured-invoice detection attempt. `not_detected` is emitted only after an applicable detection path completed; `inconclusive` must not be interpreted as proof that the document is not an e-invoice.
        validation_status:
          type: string
          enum: [not_applicable, valid, valid_with_warnings, invalid, unsupported, unavailable, not_evaluable]
          description: Result of the validation work in `validation_scope`. `invalid` means the applicable validation completed and failed; `not_evaluable` covers input safety, size, complexity, or well-formedness limits; `unavailable` is reserved for a technical validator dependency failure. Read `assessment` for an objective overall outcome that also accounts for source linkage.
        validation_scope:
          type: string
          enum: [xml_profile_conformance, structural_and_business, none]
          description: Exact claim supported by the validation path. `xml_profile_conformance` is limited to Standard XRechnung 3.0 and Extension XRechnung 3.0 in the identified supported XML syntax, profile, scenario, and recorded ruleset. CVD XRechnung 0.9 CII and ZUGFeRD 1.0 COMFORT report `structural_and_business`, which denotes deterministic parser, structure, business, and arithmetic checks without claiming complete official profile conformance. `none` means no conformance validation completed.
        assessment:
          type: string
          enum: [pass, pass_with_warnings, fail, indeterminate, not_applicable]
          description: Objective overall result combining the validation outcome with structured-value authority and any required PDF/XML linkage. This is not a sender-specific allow, warn, block, or retry policy and is not a statement of legal validity.
        validator:
          type: object
          nullable: true
          additionalProperties: false
          description: Validation-engine and ruleset identity persisted with this run. Null when no external or officially versioned conformance engine applied.
          properties:
            engine:
              type: string
              nullable: true
              example: kosit
            engine_version:
              type: string
              nullable: true
              example: 1.6.2
            configuration_version:
              type: string
              nullable: true
              example: 2026-01-31
            standard_version:
              type: string
              nullable: true
              example: 3.0.2
            scenario:
              type: string
              nullable: true
              description: Bounded scenario name reported by the validator for this run.
        finding_counts:
          type: object
          additionalProperties: false
          required: [error, warning, information]
          description: Counts of all validator messages with a supported severity before the bounded `findings` list is truncated. A message remains counted when its unsafe or malformed identifier is omitted from `findings`.
          properties:
            error:
              type: integer
              minimum: 0
            warning:
              type: integer
              minimum: 0
            information:
              type: integer
              minimum: 0
        findings:
          type: array
          maxItems: 100
          description: Bounded, deduplicated validator identifiers. Message text and document content are never included.
          items:
            type: object
            additionalProperties: false
            required: [severity, code, rule_id]
            properties:
              severity:
                type: string
                enum: [error, warning, information]
              code:
                type: string
                nullable: true
                maxLength: 128
                pattern: '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'
              rule_id:
                type: string
                nullable: true
                maxLength: 128
                pattern: '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'
        findings_truncated:
          type: boolean
          description: True when additional valid findings existed beyond the bounded returned list.
        source:
          type: string
          nullable: true
          enum: [xml, pdf_embedded_xml, email_attachment_xml]
        syntax:
          type: string
          nullable: true
          enum: [cii, ubl, legacy_zugferd_1]
        profile_identifier:
          type: string
          nullable: true
          description: Bounded profile or customization identifier declared by the structured source.
        profile_name:
          type: string
          nullable: true
          description: Resolved profile name when the declared syntax and profile are supported.
        recognized_invoice:
          type: boolean
        within_size_limit:
          type: boolean
          description: >
            Whether the XML source was within the bounded structured-invoice
            byte limit before DOM, conversion, parser, or schema work. Element
            count and nesting depth are bounded in the same place and report
            `structured_xml_complexity_limit` in `validation_errors`.
        well_formed:
          type: boolean
        safe_xml:
          type: boolean
          description: False when unsafe XML constructs such as document type or entity declarations were detected.
        parser_supported:
          type: boolean
          description: Whether the declared syntax and profile have a supported deterministic validation and extraction path.
        schema_valid:
          type: boolean
          description: Whether the applicable structured-invoice structural constraints passed.
        schema_violation_count:
          type: integer
          nullable: true
          minimum: 0
        business_rules_valid:
          type: boolean
          description: Whether required invoice values and monetary/tax arithmetic invariants passed.
        authority:
          type: string
          enum: [accepted, rejected, not_applicable]
          description: Whether structured values were permitted to become authoritative.
        linkage_checked:
          type: boolean
        linkage_source:
          type: string
          nullable: true
          enum: [pdf_visible_text, email_pdf_attachment]
        linked:
          type: boolean
          nullable: true
          description: Null when no paired human-readable representation was applicable.
        validation_errors:
          type: array
          items:
            type: string
          description: >
            Stable document-data-free validation reasons, including size-limit,
            complexity-limit, syntax/profile, arithmetic, source-linkage, and
            bounded embedded extraction failures. A PDF with multiple recognized
            invoice XML attachments reports
            `multiple_embedded_invoice_xml_attachments` instead of selecting one.
        validation_rule_ids:
          type: array
          items:
            type: string
          maxItems: 100
          description: >
            Bounded, document-data-free KoSIT or ZUGFeRD Schematron rule
            identifiers when native validation reports specific conformance
            failures. Empty when no rule identifiers are available.
        matched_fields:
          type: array
          items:
            type: string
          description: Critical field names confirmed by the paired human-readable source; values are never exposed here.
        conflict_fields:
          type: array
          items:
            type: string
          description: Critical field names that contradicted the paired human-readable source.
        unverified_fields:
          type: array
          items:
            type: string
          description: Critical field names not independently visible in the paired source.
    SectorExtractionSummary:
      type: object
      description: Compact specialized profile result returned under `sector_extraction_summary` on the document resource. Its fields and export descriptors are profile-neutral. The German energy profile is the currently available example.
      required: [id, extraction_run_id, profile, profile_version, schema_version, machine_outcome, effective_outcome, handoff_status, review_reasons, handoff_review_reasons, warnings, lock_version, etag, extractions_url, exports]
      properties:
        id:
          type: integer
          example: 789
        extraction_run_id:
          type: integer
          example: 456
        profile:
          type: string
          example: de.energy.supply-invoice
          description: Canonical extraction profile key selected at upload.
        profile_version:
          type: string
          example: "2.0.1"
        schema_version:
          type: string
          example: "2.0.0"
        machine_outcome:
          $ref: "#/components/schemas/ProfileMachineOutcome"
        effective_outcome:
          $ref: "#/components/schemas/ProfileEffectiveOutcome"
        handoff_status:
          $ref: "#/components/schemas/ProfileHandoffStatus"
        review_reasons:
          type: array
          items:
            type: string
          example: [ocr_character_ambiguity]
        handoff_review_reasons:
          type: array
          items:
            type: string
          example: []
        warnings:
          type: array
          items:
            type: string
          example: [supplementary_portal_component_present]
        lock_version:
          type: integer
          minimum: 0
        etag:
          type: string
          example: '"extraction-result-789-v0"'
        extractions_url:
          type: string
          format: uri
          example: https://api.exdata.app/v1/documents/123/extractions
        exports:
          $ref: "#/components/schemas/SectorExtractionExports"
    SectorExtraction:
      type: object
      description: Complete profile-neutral result envelope returned under `sector_extraction` by the document extractions endpoint. The mutually exclusive `profile` constraints select either a known typed profile contract or the generic fallback used by future profiles; no OpenAPI discriminator is declared because OpenAPI 3.0 has no standards-based wildcard mapping for future profile keys. German energy supply invoices follow `GermanEnergySectorExtraction`; a canonical failed result can return null machine and effective payloads when no finalized usable profile payload exists, including when finalization fails after provisional result persistence.
      oneOf:
        - $ref: "#/components/schemas/GermanEnergySectorExtraction"
        - $ref: "#/components/schemas/GenericSectorExtraction"
      required: [id, document_id, extraction_run_id, profile, profile_version, schema_version, machine_outcome, effective_outcome, handoff_status, review_reasons, handoff_review_reasons, warnings, lock_version, etag, acceptance_source, reviewed_at, machine_payload, effective_payload, validation_summary, source_components, review_decisions, exports, created_at, updated_at]
      properties:
        id:
          type: integer
          example: 789
        document_id:
          type: integer
          example: 123
        extraction_run_id:
          type: integer
          example: 456
        profile:
          type: string
          example: de.energy.supply-invoice
          description: Canonical extraction profile key selected at upload.
        profile_version:
          type: string
          example: "2.0.1"
        schema_version:
          type: string
          example: "2.0.0"
        machine_outcome:
          $ref: "#/components/schemas/ProfileMachineOutcome"
        effective_outcome:
          $ref: "#/components/schemas/ProfileEffectiveOutcome"
        handoff_status:
          $ref: "#/components/schemas/ProfileHandoffStatus"
        review_reasons:
          type: array
          items:
            type: string
          example: [ocr_character_ambiguity]
        handoff_review_reasons:
          type: array
          items:
            type: string
          example: []
        warnings:
          type: array
          items:
            type: string
          example: [supplementary_portal_component_present]
        lock_version:
          type: integer
          minimum: 0
          example: 0
        etag:
          type: string
          example: '"extraction-result-789-v0"'
        acceptance_source:
          type: string
          nullable: true
          enum: [machine, human_review]
        reviewed_at:
          type: string
          format: date-time
          nullable: true
        machine_payload:
          type: object
          nullable: true
          additionalProperties: true
          description: Immutable normalized result produced by the extraction run. Its versioned shape is defined by `profile` and `schema_version`. Null on a canonical failed result when no finalized usable profile payload exists, including when finalization replaces an earlier provisional result. Properties named `evidence` are recursively omitted unless `include=evidence` is requested.
        effective_payload:
          type: object
          nullable: true
          additionalProperties: true
          description: Current profile-defined result. It initially equals `machine_payload` and changes only through audited review decisions. Null when the canonical failed result has no finalized usable machine payload. Properties named `evidence` are recursively omitted unless `include=evidence` is requested.
        validation_summary:
          $ref: "#/components/schemas/ProfileValidationSummary"
        source_components:
          type: array
          items:
            $ref: "#/components/schemas/ProfileSourceComponent"
        evidence:
          type: array
          description: Flattened evidence collection included only when `include=evidence` is requested.
          items:
            $ref: "#/components/schemas/ProfileEvidence"
        evidence_pages:
          type: array
          description: Sorted descriptors for physical pages cited by this exact profile result. Included only with `include=evidence`. A missing or expired artifact remains explicit with `available=false` and `preview_url=null`; exdata never substitutes a page from another run.
          items:
            $ref: "#/components/schemas/ProfileEvidencePage"
        review_decisions:
          type: array
          items:
            $ref: "#/components/schemas/ProfileReviewDecision"
        exports:
          $ref: "#/components/schemas/SectorExtractionExports"
        created_at:
          type: string
          format: date-time
          nullable: true
        updated_at:
          type: string
          format: date-time
          nullable: true
    GermanEnergySectorExtraction:
      type: object
      description: Typed branch selected when `profile` is `de.energy.supply-invoice`. The common result envelope remains defined by `SectorExtraction`.
      required: [profile, profile_version, schema_version, machine_payload, effective_payload, source_components, exports]
      properties:
        profile:
          type: string
          enum: [de.energy.supply-invoice]
        profile_version:
          type: string
          enum: ["2.0.0", "2.0.1"]
        schema_version:
          type: string
          enum: ["2.0.0"]
        machine_payload:
          oneOf:
            - $ref: "#/components/schemas/GermanEnergyPacketPayload"
            - $ref: "#/components/schemas/ProfileNullValue"
          description: Immutable normalized German energy packet, or null on a canonical failed result when no finalized usable profile payload exists, including after failed finalization of a provisional result.
        effective_payload:
          oneOf:
            - $ref: "#/components/schemas/GermanEnergyPacketPayload"
            - $ref: "#/components/schemas/ProfileNullValue"
          description: Current reviewed German energy packet, or null when the canonical failed result has no finalized usable machine payload. A field review changes only the invoice named by the decision's `invoice_ref`.
        source_components:
          type: array
          items:
            $ref: "#/components/schemas/GermanEnergyPacketSourceComponent"
        exports:
          $ref: "#/components/schemas/GermanEnergyExports"
    GenericSectorExtraction:
      type: object
      description: Extensible fallback for every profile without a dedicated typed OpenAPI branch. Profile-specific payload fields remain versioned by `profile` and `schema_version`.
      required: [profile, machine_payload, effective_payload]
      properties:
        profile:
          type: string
          not:
            enum: [de.energy.supply-invoice]
          description: Canonical profile key not covered by a dedicated typed branch in this contract.
        machine_payload:
          type: object
          nullable: true
          additionalProperties: true
        effective_payload:
          type: object
          nullable: true
          additionalProperties: true
    ProfileNullValue:
      type: object
      nullable: true
      enum: [null]
      description: Reusable explicit OpenAPI 3.0 null branch for a nullable profile object referenced through `oneOf`.
    SectorExtractionExports:
      type: object
      description: Export descriptors registered by the selected profile, keyed by a stable API field name. The `url` remains present even while `available=false`; call it only after availability becomes true.
      additionalProperties:
        $ref: "#/components/schemas/ProfileExportDescriptor"
    GermanEnergyExports:
      type: object
      additionalProperties: false
      description: Export descriptors returned by German energy full-invoice profile versions 2.0.0 and 2.0.1. A descriptor becomes available only after the effective result and handoff are both accepted.
      required: [canonical_json, invoice_lines_csv]
      properties:
        canonical_json:
          allOf:
            - $ref: "#/components/schemas/ProfileExportDescriptor"
          description: Complete deterministic packet-shaped JSON snapshot at `canonical.json`, using contract `de-energy-canonical-json:2.0.0`.
        invoice_lines_csv:
          allOf:
            - $ref: "#/components/schemas/ProfileExportDescriptor"
          description: One deterministic CSV row per canonical charge line across every returned invoice at `invoice-lines.csv`, using contract `de-energy-invoice-lines-csv:2.0.0`. Invoice identity and page ownership lead each row. This projection also supports batch downloads.
    GermanEnergyCanonicalExport:
      type: object
      additionalProperties: false
      description: Deterministic `canonical.json` export for one accepted German energy packet result.
      required: [profile, profile_version, schema_version, effective_outcome, effective_payload]
      properties:
        profile:
          type: string
          enum: [de.energy.supply-invoice]
        profile_version:
          type: string
          enum: ["2.0.0", "2.0.1"]
        schema_version:
          type: string
          enum: ["2.0.0"]
        effective_outcome:
          type: string
          enum: [accepted]
        effective_payload:
          $ref: "#/components/schemas/GermanEnergyPacketPayload"
    GermanEnergyInvoiceLinesCsv:
      type: string
      format: binary
      description: UTF-8 CSV with one row per canonical charge line. The leading invoice columns preserve independently issued invoice identity and page ownership. Documents are sorted by ID in batch output; invoices remain in source order inside each document, and line order is preserved inside each invoice. Formula-leading text is apostrophe-prefixed while valid signed numeric cells remain numeric.
      x-columns: [invoice_ref, invoice_ordinal, invoice_start_page, invoice_end_page, document_id, profile_result_id, document_ref, document_number, supply_point_ref, market_location_id, settlement_ref, charge_line_ref, component_ref, scope_type, scope_ref, commodity, category, description, period_start, period_end, quantity, quantity_unit, unit_price_amount, unit_price_currency, unit_price_currency_scale, unit_price_basis_quantity, unit_price_basis_unit, net_amount, tax_rate, tax_amount, gross_amount, currency, effect]
    ProfileExportDescriptor:
      type: object
      required: [url, version, available]
      properties:
        url:
          type: string
          format: uri
          example: https://api.exdata.app/v1/documents/123/exports/canonical.json
        version:
          type: string
          example: de-energy-canonical-json:2.0.0
          description: Versioned projection contract used to render this export.
        available:
          type: boolean
          example: true
          description: True when the extraction is finalized and the selected projection's readiness requirements pass. False means the URL is stable but a download currently returns `409 profile_export_not_ready`.
    ProfileEvidencePage:
      type: object
      required: [physical_page, available, preview_url]
      properties:
        physical_page:
          type: integer
          minimum: 1
          maximum: 99999
          example: 1
        available:
          type: boolean
          description: Whether the safe persisted artifact for this exact extraction run and physical page can currently be downloaded.
          example: true
        preview_url:
          type: string
          format: uri
          nullable: true
          description: Protected run-bound preview URL when available; otherwise null. It never points to a page from another extraction run.
          example: https://api.exdata.app/v1/documents/123/extraction-runs/456/pages/1/preview
    ProfileExportNotReadyError:
      allOf:
        - $ref: "#/components/schemas/ErrorEnvelope"
        - type: object
          properties:
            code:
              type: string
              enum: [profile_export_not_ready]
            document_id:
              type: integer
              description: Single-document export only.
            profile_result_id:
              type: integer
              description: Single-document export only.
            effective_outcome:
              $ref: "#/components/schemas/ProfileEffectiveOutcome"
            handoff_status:
              $ref: "#/components/schemas/ProfileHandoffStatus"
            document_ids:
              type: array
              description: Batch export only. Contains requested document IDs whose profile result is missing or not accepted for handoff.
              items:
                type: integer
    ProfileExportIncompatibleError:
      allOf:
        - $ref: "#/components/schemas/ErrorEnvelope"
        - type: object
          properties:
            code:
              type: string
              enum: [profile_export_incompatible]
    ProfileMachineOutcome:
      type: string
      enum: [accepted, needs_review, unsupported, failed]
    ProfileEffectiveOutcome:
      type: string
      enum: [accepted, needs_review, unsupported, failed, rejected]
    ProfileHandoffStatus:
      type: string
      enum: [accepted, needs_review, unsupported, rejected]
    AcceptedProfileHandoffWebhook:
      type: object
      description: Signed `extraction.handoff.accepted` webhook payload. It is created only when both the effective profile outcome and downstream handoff are accepted. The accepted result snapshot is recorded at first persistence and emitted at most once per subscribed endpoint and extraction run; normal webhook delivery retries can resend the same delivery ID.
      required: [id, type, created_at, data]
      properties:
        id:
          type: string
          format: uuid
          description: Delivery ID, identical to `X-Delivery`.
        type:
          type: string
          enum: [extraction.handoff.accepted]
        created_at:
          type: string
          format: date-time
        data:
          type: object
          required: [profile_result]
          properties:
            profile_result:
              $ref: "#/components/schemas/AcceptedProfileHandoffResult"
    AcceptedProfileHandoffResult:
      type: object
      description: Immutable accepted profile-result snapshot for downstream automation. Mutually exclusive `profile` constraints select a known typed payload branch or the generic fallback for future profiles; no OpenAPI discriminator is declared because OpenAPI 3.0 has no standards-based wildcard mapping for future profile keys. This is a webhook payload object, not a separate REST endpoint.
      oneOf:
        - $ref: "#/components/schemas/GermanEnergyAcceptedProfileHandoffResult"
        - $ref: "#/components/schemas/GenericAcceptedProfileHandoffResult"
      required: [id, account_id, document_id, extraction_run_id, profile, profile_version, schema_version, machine_outcome, effective_outcome, handoff_status, acceptance_source, reviewed_at, lock_version, etag, review_reasons, handoff_review_reasons, warnings, effective_payload, validation_summary, source_components, evidence, created_at, updated_at]
      properties:
        id:
          type: integer
        account_id:
          type: integer
        document_id:
          type: integer
        extraction_run_id:
          type: integer
        profile:
          type: string
          example: de.energy.supply-invoice
        profile_version:
          type: string
          example: "2.0.1"
        schema_version:
          type: string
          example: "2.0.0"
        machine_outcome:
          $ref: "#/components/schemas/ProfileMachineOutcome"
        effective_outcome:
          type: string
          enum: [accepted]
        handoff_status:
          type: string
          enum: [accepted]
        acceptance_source:
          type: string
          enum: [machine, human_review]
        reviewed_at:
          type: string
          format: date-time
          nullable: true
        lock_version:
          type: integer
          minimum: 0
        etag:
          type: string
          example: '"extraction-result-789-v1"'
        review_reasons:
          type: array
          items:
            type: string
        handoff_review_reasons:
          type: array
          items:
            type: string
        warnings:
          type: array
          items:
            type: string
        effective_payload:
          type: object
          additionalProperties: true
          description: Accepted profile-defined payload that downstream consumers can treat as final for this extraction run.
        validation_summary:
          type: object
          additionalProperties: true
        source_components:
          type: array
          items:
            $ref: "#/components/schemas/ProfileSourceComponent"
        evidence:
          type: array
          items:
            $ref: "#/components/schemas/ProfileEvidence"
        created_at:
          type: string
          format: date-time
          nullable: true
        updated_at:
          type: string
          format: date-time
          nullable: true
    GermanEnergyAcceptedProfileHandoffResult:
      type: object
      description: Typed accepted-handoff branch for the German energy supply-invoice profile.
      required: [profile, profile_version, schema_version, effective_payload, source_components]
      properties:
        profile:
          type: string
          enum: [de.energy.supply-invoice]
        profile_version:
          type: string
          enum: ["2.0.0", "2.0.1"]
        schema_version:
          type: string
          enum: ["2.0.0"]
        effective_payload:
          allOf:
            - $ref: "#/components/schemas/GermanEnergyPacketPayload"
        source_components:
          type: array
          items:
            $ref: "#/components/schemas/GermanEnergyPacketSourceComponent"
    GenericAcceptedProfileHandoffResult:
      type: object
      description: Extensible accepted-handoff fallback for profiles without a dedicated typed OpenAPI branch.
      required: [profile, effective_payload]
      properties:
        profile:
          type: string
          not:
            enum: [de.energy.supply-invoice]
        effective_payload:
          type: object
          additionalProperties: true
    GermanEnergyPacketPayload:
      type: object
      additionalProperties: false
      description: Stable schema 2.0.0 payload used by German energy full-invoice profile versions 2.0.0 and 2.0.1. Packet metadata accounts for the physical document, while `invoices` contains one source-ordered result per independently issued invoice. A single-invoice PDF still uses `invoices[0]`; a source-verified non-invoice uses `invoices=[]` and an unsupported result outcome.
      required: [packet, invoices]
      properties:
        packet:
          $ref: "#/components/schemas/GermanEnergyPacket"
        invoices:
          type: array
          description: Independently issued invoices in physical source order. Data and references are scoped to each item and are never combined across invoice page ranges.
          items:
            $ref: "#/components/schemas/GermanEnergyInvoiceResult"
    GermanEnergyPacket:
      type: object
      additionalProperties: false
      description: Physical-document classification, page accounting, and packet-level review state.
      required: [ref, classification, physical_page_count, unassigned_pages, unassigned_physical_pages, blockers, review_reasons, warnings]
      properties:
        ref:
          type: string
          description: Stable reference for this uploaded PDF packet.
          example: packet_123
        classification:
          $ref: "#/components/schemas/GermanEnergyPacketClassification"
        physical_page_count:
          type: integer
          minimum: 0
          description: Number of physical PDF pages considered by the profile.
          example: 8
        unassigned_pages:
          type: array
          description: Pages not owned by an invoice, with a source-backed classification when available. An `ambiguous` page prevents packet acceptance.
          items:
            $ref: "#/components/schemas/GermanEnergyUnassignedPage"
        unassigned_physical_pages:
          type: array
          description: Sorted physical page numbers from `unassigned_pages`, provided for convenient routing.
          items:
            type: integer
            minimum: 1
        blockers:
          type: array
          description: Boundary or page-ownership problems that prevent invoice data from crossing an uncertain packet boundary.
          items:
            $ref: "#/components/schemas/GermanEnergyPacketBlocker"
        review_reasons:
          type: array
          description: Packet-level reasons that require human review.
          items:
            type: string
        warnings:
          type: array
          description: Non-blocking packet-level warnings.
          items:
            type: string
    GermanEnergyPacketClassification:
      type: object
      additionalProperties: false
      required: [kind, document_kind]
      properties:
        kind:
          type: string
          enum: [invoice_packet, non_invoice, unknown]
          description: Whether the PDF contains at least one independently issued energy invoice, is directly evidenced as a non-invoice, or remains ambiguous.
        document_kind:
          type: string
          nullable: true
          enum: [annual_invoice, final_invoice, periodic_invoice, monthly_invoice, invoice, contract_confirmation, advance_payment_notice, price_notice, welcome_letter, tariff_notice, energy_mix_annex, other, unknown]
          description: Source-backed document kind for the packet classification, or null when it cannot be established.
        evidence:
          description: Bounded classification evidence. Included only when `include=evidence` is requested; an empty array represents unavailable evidence in the canonical export.
          oneOf:
            - $ref: "#/components/schemas/GermanEnergyPacketClassificationEvidence"
            - type: array
              maxItems: 0
    GermanEnergyPacketClassificationEvidence:
      type: object
      additionalProperties: false
      required: [physical_page, evidence_text, component_ref]
      properties:
        physical_page:
          type: integer
          nullable: true
          minimum: 1
        evidence_text:
          type: string
          nullable: true
          description: Literal text from the claimed physical page supporting the classification.
        component_ref:
          type: string
          nullable: true
          description: Invoice-scoped source component when the evidence belongs to an invoice page.
    GermanEnergyUnassignedPage:
      type: object
      additionalProperties: false
      required: [physical_page, classification]
      properties:
        physical_page:
          type: integer
          minimum: 1
        classification:
          type: string
          enum: [blank, cover, non_invoice, ambiguous]
        evidence:
          description: Same-page evidence for a cover or non-invoice classification. Included only when `include=evidence` is requested; an empty array represents no bounded evidence in the canonical export.
          oneOf:
            - $ref: "#/components/schemas/GermanEnergyPacketClassificationEvidence"
            - type: array
              maxItems: 0
    GermanEnergyPacketBlocker:
      type: object
      additionalProperties: false
      required: [code, phase, invoice_ref, physical_pages]
      properties:
        code:
          type: string
          description: Stable packet-boundary review code.
          example: document_structure_ambiguous
        phase:
          type: string
          nullable: true
          enum: [identity_topology, technical_details, financial_details, component_merge]
          description: Data group in which the boundary problem was detected, when available.
        invoice_ref:
          type: string
          nullable: true
          description: Affected invoice when the problem can be isolated to one invoice.
        physical_pages:
          type: array
          description: Physical pages affected by the blocker, when known.
          items:
            type: integer
            minimum: 1
    GermanEnergyPageRange:
      type: object
      additionalProperties: false
      required: [start, end]
      properties:
        start:
          type: integer
          minimum: 1
          description: First physical page owned by the invoice.
        end:
          type: integer
          minimum: 1
          description: Last physical page owned by the invoice.
    GermanEnergyInvoiceResult:
      type: object
      additionalProperties: false
      description: One independently issued invoice and only the source-evidenced values from its owned physical pages. Use `invoice_ref` for invoice-scoped field review and joins; use `data` for invoice business fields.
      required: [invoice_ref, page_range, physical_pages, machine_outcome, effective_outcome, handoff_status, review_reasons, warnings, validation_summary, source_components, data]
      properties:
        invoice_ref:
          type: string
          description: Stable invoice reference within this packet and the required scope for field confirmation or correction.
          example: invoice_5f2db86e322d058b2bfd
        page_range:
          $ref: "#/components/schemas/GermanEnergyPageRange"
        physical_pages:
          type: array
          description: Contiguous, one-based physical PDF pages owned by this invoice.
          minItems: 1
          items:
            type: integer
            minimum: 1
        machine_outcome:
          $ref: "#/components/schemas/ProfileMachineOutcome"
        effective_outcome:
          $ref: "#/components/schemas/ProfileEffectiveOutcome"
        handoff_status:
          $ref: "#/components/schemas/ProfileHandoffStatus"
        review_reasons:
          type: array
          description: Invoice-local reasons that require review.
          items:
            type: string
        warnings:
          type: array
          description: Non-blocking invoice-local warnings.
          items:
            type: string
        validation_summary:
          allOf:
            - $ref: "#/components/schemas/ProfileValidationSummary"
          description: Validation and reconciliation details for this invoice only.
        source_components:
          type: array
          description: Invoice-scoped source groups. Every component page belongs to this invoice's `physical_pages`.
          items:
            $ref: "#/components/schemas/EnergySourceComponent"
        data:
          $ref: "#/components/schemas/GermanEnergyInvoicePayload"
    GermanEnergyPacketSourceComponent:
      type: object
      additionalProperties: false
      required: [invoice_ref, ref, kind, physical_pages, precedence]
      properties:
        invoice_ref:
          type: string
          description: Invoice that owns this source component.
        ref:
          type: string
          example: component_8a1f74f0f1d8c2ab
        kind:
          type: string
          enum: [primary_invoice, invoice_detail, portal_snapshot, annex, form, annotation, unknown]
        physical_pages:
          type: array
          items:
            type: integer
            minimum: 1
        precedence:
          type: integer
          minimum: 1
    GermanEnergyInvoicePayload:
      type: object
      additionalProperties: false
      description: Canonical business data nested under one `GermanEnergyInvoiceResult`. It preserves the source-evidenced relationships between supply points, operators, meters, readings, billed quantities, charge lines, taxes, settlement balances, and payment data for that invoice only.
      required: [document, supplier, customer, customer_relationships, supply_points, charge_lines, tax_breakdowns, settlements, payment_accounts, detected_commodities, field_quality]
      properties:
        document:
          $ref: "#/components/schemas/EnergyDocument"
        supplier:
          oneOf:
            - $ref: "#/components/schemas/EnergySupplier"
            - $ref: "#/components/schemas/ProfileNullValue"
        customer:
          oneOf:
            - $ref: "#/components/schemas/EnergyCustomer"
            - $ref: "#/components/schemas/ProfileNullValue"
        customer_relationships:
          type: array
          items:
            $ref: "#/components/schemas/EnergyCustomerRelationship"
        supply_points:
          type: array
          description: Electricity or natural-gas supply points for this independently issued invoice. Empty when the invoice pages do not provide a safely associated supply point.
          items:
            $ref: "#/components/schemas/EnergySupplyPoint"
        charge_lines:
          type: array
          description: Itemized energy, base-price, network, metering, levy, tax, discount, adjustment, and other invoice charges. Amounts use dot-decimal strings; `effect` preserves whether the row increases or decreases cost.
          items:
            $ref: "#/components/schemas/EnergyChargeLine"
        tax_breakdowns:
          type: array
          description: Document-backed tax rows linked to their document, supply point, settlement, or charge line scope.
          items:
            $ref: "#/components/schemas/EnergyTaxBreakdown"
        settlements:
          type: array
          description: Invoice totals, prior payments, adjustments, outstanding amount or credit, payment due date, payment instructions, and installment schedules.
          items:
            $ref: "#/components/schemas/EnergySettlement"
        payment_accounts:
          type: array
          description: Supplier collection or customer refund/direct-debit bank accounts shown by the invoice.
          items:
            $ref: "#/components/schemas/EnergyPaymentAccount"
        detected_commodities:
          type: array
          description: All target and non-target utility signals detected in the packet. `other` supports mixed-utility safety checks but never creates a supply point; `supply_points[].commodity` remains limited to electricity and natural gas.
          items:
            type: string
            enum: [electricity, natural_gas, other]
        field_quality:
          type: array
          items:
            $ref: "#/components/schemas/EnergyFieldQuality"
    EnergyDocument:
      type: object
      additionalProperties: false
      required: [ref, kind, document_number, issue_date, billing_period_start, billing_period_end, currency, references]
      properties:
        ref:
          type: string
          example: document_1
        kind:
          type: string
          enum: [annual_invoice, final_invoice, periodic_invoice, monthly_invoice, invoice, contract_confirmation, advance_payment_notice, price_notice, welcome_letter, tariff_notice, energy_mix_annex, other, unknown]
        document_number:
          type: string
          nullable: true
          example: RE-EXAMPLE-2025-10
        issue_date:
          type: string
          format: date
          nullable: true
          example: "2025-02-14"
        billing_period_start:
          type: string
          format: date
          nullable: true
          example: "2024-01-01"
        billing_period_end:
          type: string
          format: date
          nullable: true
          example: "2024-12-31"
        currency:
          type: string
          nullable: true
          pattern: '^[A-Z]{3}$'
          example: EUR
        references:
          type: array
          items:
            $ref: "#/components/schemas/EnergyTypedIdentifier"
    EnergySupplier:
      type: object
      additionalProperties: false
      required: [ref, legal_name, brand_name]
      properties:
        ref:
          type: string
          example: supplier_1
        legal_name:
          type: string
          nullable: true
          example: Beispiel Energie GmbH
        brand_name:
          type: string
          nullable: true
    EnergyCustomer:
      type: object
      additionalProperties: false
      required: [ref, name, billing_address]
      properties:
        ref:
          type: string
          example: customer_1
        name:
          type: string
          nullable: true
          example: Musterkunde GmbH
        billing_address:
          oneOf:
            - $ref: "#/components/schemas/EnergyAddress"
            - $ref: "#/components/schemas/ProfileNullValue"
    EnergyAddress:
      type: object
      additionalProperties: false
      required: [raw, street, house_number, postal_code, city, country_code]
      properties:
        raw:
          type: string
          nullable: true
          example: Musterstraße 14, 70173 Stuttgart
        street:
          type: string
          nullable: true
          example: Musterstraße
        house_number:
          type: string
          nullable: true
          example: "14"
        postal_code:
          type: string
          nullable: true
          example: "70173"
        city:
          type: string
          nullable: true
          example: Stuttgart
        country_code:
          type: string
          nullable: true
          pattern: '^[A-Z]{2}$'
          example: DE
    EnergyCustomerRelationship:
      type: object
      additionalProperties: false
      required: [ref, supplier_ref, customer_ref, supply_point_refs, identifiers]
      properties:
        ref:
          type: string
          example: relationship_1
        supplier_ref:
          type: string
          example: supplier_1
        customer_ref:
          type: string
          example: customer_1
        supply_point_refs:
          type: array
          items:
            type: string
          example: [supply_point_1]
        identifiers:
          type: array
          items:
            $ref: "#/components/schemas/EnergyTypedIdentifier"
    EnergyTypedIdentifier:
      type: object
      additionalProperties: false
      required: [type, value, normalized_value, scope_type, entity_ref, lineage, valid_from, valid_to, status]
      properties:
        type:
          type: string
          enum: [invoice_number, internal_document_reference, customer_number, customer_debtor_number, business_partner_number, membership_number, contract_account, contract_number, mandate_id, market_location_id, metering_location_id, legacy_metering_point_id, meter_number, operator_code]
          description: The domain enum is wider than either identifier collection. German energy full-invoice profile versions 2.0.0 and 2.0.1 emit invoice_number, internal_document_reference, customer_number, customer_debtor_number, business_partner_number, membership_number, contract_account, and contract_number under `document.references` or `customer_relationships[].identifiers` according to their document-backed scope. MaLo, legacy metering-point IDs, MeLo, meter numbers, and operator codes are scalar properties on their owning objects.
        value:
          type: string
          nullable: true
        normalized_value:
          type: string
          nullable: true
        scope_type:
          type: string
          enum: [document, customer_relationship, supply_point, metering_location, meter_assignment]
        entity_ref:
          type: string
        lineage:
          type: string
          enum: [current, former, successor, unknown]
        valid_from:
          type: string
          format: date
          nullable: true
        valid_to:
          type: string
          format: date
          nullable: true
        status:
          $ref: "#/components/schemas/EnergyFieldStatus"
    EnergySupplyPoint:
      type: object
      additionalProperties: false
      required: [ref, commodity, service_address, market_location_id, legacy_metering_point_id, metering_locations, meter_assignments, product_name, tariff_name, operators, registers, readings, measurements, gas_conversion_segments]
      properties:
        ref:
          type: string
          example: supply_point_1
        commodity:
          type: string
          enum: [electricity, natural_gas]
        service_address:
          oneOf:
            - $ref: "#/components/schemas/EnergyAddress"
            - $ref: "#/components/schemas/ProfileNullValue"
        market_location_id:
          type: string
          nullable: true
          description: German MaLo identifier in its source/display form. After display whitespace is removed, the value is 11 digits, starts with 1–9, and has a valid check digit.
          example: "12345678905"
        legacy_metering_point_id:
          type: string
          nullable: true
        metering_locations:
          type: array
          items:
            $ref: "#/components/schemas/EnergyMeteringLocation"
        meter_assignments:
          type: array
          items:
            $ref: "#/components/schemas/EnergyMeterAssignment"
        product_name:
          type: string
          nullable: true
          description: Supplier product name printed on the invoice.
          example: GasFix 24
        tariff_name:
          type: string
          nullable: true
          description: Tariff name printed on the invoice.
          example: Business Gas 2024
        operators:
          type: array
          items:
            $ref: "#/components/schemas/EnergyOperator"
        registers:
          type: array
          items:
            $ref: "#/components/schemas/EnergyMeterRegister"
        readings:
          type: array
          items:
            $ref: "#/components/schemas/EnergyMeterReading"
        measurements:
          type: array
          items:
            $ref: "#/components/schemas/EnergyMeasurement"
        gas_conversion_segments:
          type: array
          description: Natural-gas volume-to-energy calculations. Empty for electricity supply points and when no conversion values are shown.
          items:
            $ref: "#/components/schemas/EnergyGasConversionSegment"
    EnergyMeteringLocation:
      type: object
      additionalProperties: false
      required: [ref, metering_location_id]
      properties:
        ref:
          type: string
          example: metering_location_1
        metering_location_id:
          type: string
          nullable: true
          description: German MeLo identifier. After display whitespace is removed, the value is DE followed by 31 letters or digits.
          example: DEEXAMPLE000000000000000000000000
    EnergyMeterAssignment:
      type: object
      additionalProperties: false
      required: [ref, metering_location_ref, meter_number, component_ref, observed_from, observed_to, installed_at, removed_at]
      properties:
        ref:
          type: string
          example: meter_assignment_1
        metering_location_ref:
          type: string
          nullable: true
        meter_number:
          type: string
          nullable: true
          description: Meter identifier with 4–32 letters, digits, dots, underscores, slashes, or hyphens and at least one digit.
          example: MTR-EXAMPLE-001
        component_ref:
          type: string
          nullable: true
        observed_from:
          type: string
          format: date
          nullable: true
        observed_to:
          type: string
          format: date
          nullable: true
        installed_at:
          type: string
          format: date
          nullable: true
          description: Reserved lifecycle field. German energy full-invoice profile versions 2.0.0 and 2.0.1 return null; use `observed_from`, `observed_to`, and readings with `reading_role=meter_installation` for document-backed history.
        removed_at:
          type: string
          format: date
          nullable: true
          description: Reserved lifecycle field. German energy full-invoice profile versions 2.0.0 and 2.0.1 return null; use `observed_from`, `observed_to`, and readings with `reading_role=meter_removal` for document-backed history.
    EnergyOperator:
      type: object
      additionalProperties: false
      required: [ref, supply_point_ref, role, name, operator_code, valid_from, valid_to]
      properties:
        ref:
          type: string
          example: operator_1
        supply_point_ref:
          type: string
          example: supply_point_1
        role:
          type: string
          nullable: true
          enum: [grid_operator, metering_operator]
        name:
          type: string
          nullable: true
          example: Beispiel Netze GmbH
        operator_code:
          type: string
          nullable: true
          description: Operator identifier in its source/display form.
        valid_from:
          type: string
          format: date
          nullable: true
        valid_to:
          type: string
          format: date
          nullable: true
    EnergyMeterRegister:
      type: object
      additionalProperties: false
      required: [ref, supply_point_ref, scope_type, scope_ref, register_code, measurement_kind, direction, unit]
      properties:
        ref:
          type: string
          example: register_1
        supply_point_ref:
          type: string
          example: supply_point_1
        scope_type:
          $ref: "#/components/schemas/EnergyMeterScopeType"
        scope_ref:
          type: string
          nullable: true
          description: Referenced supply point, metering location, or meter assignment named by `scope_type`.
        register_code:
          type: string
          nullable: true
          example: 1.8.0
        measurement_kind:
          type: string
          nullable: true
          enum: [active_energy, reactive_energy, demand, gas_volume, other]
        direction:
          type: string
          nullable: true
          enum: [consumption, feed_in, bidirectional, other]
        unit:
          $ref: "#/components/schemas/EnergyNullableUnit"
    EnergyMeterReading:
      type: object
      additionalProperties: false
      required: [ref, supply_point_ref, scope_type, scope_ref, register_ref, reading_role, read_at, value, unit, read_method, raw_read_method]
      properties:
        ref:
          type: string
          example: reading_1
        supply_point_ref:
          type: string
          example: supply_point_1
        scope_type:
          $ref: "#/components/schemas/EnergyMeterScopeType"
        scope_ref:
          type: string
          nullable: true
        register_ref:
          type: string
          nullable: true
          example: register_1
        reading_role:
          type: string
          nullable: true
          enum: [period_start, period_end, intermediate, meter_installation, meter_removal, comparison, other]
        read_at:
          type: string
          format: date
          nullable: true
        value:
          $ref: "#/components/schemas/EnergyNullableDecimal"
        unit:
          $ref: "#/components/schemas/EnergyNullableUnit"
        read_method:
          type: string
          nullable: true
          enum: [customer_read, network_read, remote_read, load_profile, calculated, estimated, substitute_value, other]
        raw_read_method:
          type: string
          nullable: true
          description: Source-language reading-method text when present.
          example: rechnerisch ermittelt
    EnergyMeasurement:
      type: object
      additionalProperties: false
      required: [ref, supply_point_ref, scope_type, scope_ref, register_ref, kind, quantity, unit, period_start, period_end, energy_basis, context, summary_level]
      properties:
        ref:
          type: string
          example: measurement_1
        supply_point_ref:
          type: string
          example: supply_point_1
        scope_type:
          $ref: "#/components/schemas/EnergyMeterScopeType"
        scope_ref:
          type: string
          nullable: true
        register_ref:
          type: string
          nullable: true
        kind:
          type: string
          nullable: true
          enum: [billed_energy, metered_energy, reactive_energy, measured_demand, billed_demand, gas_volume, other]
        quantity:
          $ref: "#/components/schemas/EnergyNullableDecimal"
        unit:
          $ref: "#/components/schemas/EnergyNullableUnit"
        period_start:
          type: string
          format: date
          nullable: true
        period_end:
          type: string
          format: date
          nullable: true
        energy_basis:
          type: string
          nullable: true
          enum: [gross_calorific_value_hs, net_calorific_value_hi, other]
        context:
          type: string
          nullable: true
          enum: [current_billing_period, historical_comparison, forecast, disclosure, other]
        summary_level:
          type: string
          nullable: true
          enum: [detail, summary]
    EnergyGasConversionSegment:
      type: object
      additionalProperties: false
      required: [ref, supply_point_ref, scope_type, scope_ref, register_ref, start_reading_ref, end_reading_ref, measurement_ref, period_start, period_end, volume_difference, volume_unit, condition_number, calorific_value, calorific_value_unit, energy_basis, calculated_energy, energy_unit]
      properties:
        ref:
          type: string
          example: gas_conversion_segment_1
        supply_point_ref:
          type: string
          example: supply_point_1
        scope_type:
          $ref: "#/components/schemas/EnergyMeterScopeType"
        scope_ref:
          type: string
          nullable: true
        register_ref:
          type: string
          nullable: true
        start_reading_ref:
          type: string
          nullable: true
        end_reading_ref:
          type: string
          nullable: true
        measurement_ref:
          type: string
          nullable: true
        period_start:
          type: string
          format: date
          nullable: true
        period_end:
          type: string
          format: date
          nullable: true
        volume_difference:
          $ref: "#/components/schemas/EnergyNullableDecimal"
        volume_unit:
          type: string
          nullable: true
          enum: [m3]
        condition_number:
          $ref: "#/components/schemas/EnergyNullableDecimal"
        calorific_value:
          $ref: "#/components/schemas/EnergyNullableDecimal"
        calorific_value_unit:
          type: string
          nullable: true
          enum: [kWh/m3]
        energy_basis:
          type: string
          nullable: true
          enum: [gross_calorific_value_hs, net_calorific_value_hi, other]
        calculated_energy:
          $ref: "#/components/schemas/EnergyNullableDecimal"
        energy_unit:
          type: string
          nullable: true
          enum: [Wh, kWh, MWh]
    EnergyChargeLine:
      type: object
      additionalProperties: false
      required: [ref, scope_type, scope_ref, supply_point_ref, settlement_ref, component_ref, commodity, category, description, period_start, period_end, quantity, quantity_unit, unit_price_amount, unit_price_currency, unit_price_currency_scale, unit_price_basis_quantity, unit_price_basis_unit, net_amount, tax_rate, tax_amount, gross_amount, currency, effect]
      properties:
        ref:
          type: string
          example: charge_line_1
        scope_type:
          type: string
          enum: [document, supply_point]
        scope_ref:
          type: string
          nullable: true
        supply_point_ref:
          type: string
          nullable: true
        settlement_ref:
          type: string
          nullable: true
        component_ref:
          type: string
          nullable: true
          description: Source component containing the charge line when one component can be selected.
        commodity:
          $ref: "#/components/schemas/EnergyNullableCommodity"
        category:
          type: string
          nullable: true
          enum: [energy_consumption, base_price, demand_price, metering, meter_operation, grid_usage, concession_fee, levy, energy_tax, carbon_cost, discount, relief, surcharge, service_fee, adjustment, other]
        description:
          type: string
          nullable: true
          example: Energy charge (Arbeitspreis)
        period_start:
          type: string
          format: date
          nullable: true
        period_end:
          type: string
          format: date
          nullable: true
        quantity:
          $ref: "#/components/schemas/EnergyNullableDecimal"
        quantity_unit:
          $ref: "#/components/schemas/EnergyNullableUnit"
        unit_price_amount:
          $ref: "#/components/schemas/EnergyNullableDecimal"
        unit_price_currency:
          $ref: "#/components/schemas/EnergyNullableCurrency"
        unit_price_currency_scale:
          type: string
          nullable: true
          enum: [major_unit, cent]
        unit_price_basis_quantity:
          $ref: "#/components/schemas/EnergyNullableDecimal"
        unit_price_basis_unit:
          $ref: "#/components/schemas/EnergyNullableUnit"
        net_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        tax_rate:
          $ref: "#/components/schemas/EnergyNullableTaxRate"
        tax_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        gross_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        currency:
          $ref: "#/components/schemas/EnergyNullableCurrency"
        effect:
          type: string
          nullable: true
          enum: [increases_cost, decreases_cost]
    EnergyTaxBreakdown:
      type: object
      additionalProperties: false
      required: [ref, scope_type, scope_ref, supply_point_ref, settlement_ref, charge_line_ref, commodity, taxable_amount, tax_amount, tax_rate, taxability, tax_collection_mechanism, tax_exemption_reason, currency]
      properties:
        ref:
          type: string
          example: tax_breakdown_1
        scope_type:
          type: string
          enum: [document, supply_point, settlement, charge_line]
        scope_ref:
          type: string
          nullable: true
        supply_point_ref:
          type: string
          nullable: true
        settlement_ref:
          type: string
          nullable: true
        charge_line_ref:
          type: string
          nullable: true
        commodity:
          $ref: "#/components/schemas/EnergyNullableCommodity"
        taxable_amount:
          $ref: "#/components/schemas/EnergyNullableSignedAmount"
        tax_amount:
          $ref: "#/components/schemas/EnergyNullableSignedAmount"
        tax_rate:
          $ref: "#/components/schemas/EnergyNullableTaxRate"
        taxability:
          type: string
          nullable: true
          enum: [taxable, zero_rated, exempt, out_of_scope]
        tax_collection_mechanism:
          type: string
          nullable: true
          enum: [seller_collected, reverse_charge, buyer_use_tax, not_collected]
        tax_exemption_reason:
          type: string
          nullable: true
        currency:
          $ref: "#/components/schemas/EnergyNullableCurrency"
    EnergySettlement:
      type: object
      additionalProperties: false
      required: [ref, scope_type, scope_ref, supply_point_ref, commodity, currency, net_amount, tax_amount, gross_amount, advance_payments_amount, other_payments_amount, adjustments, balance_kind, balance_amount, payment_due_date, disposition, installment_plans]
      properties:
        ref:
          type: string
          example: settlement_1
        scope_type:
          type: string
          enum: [document, supply_point]
        scope_ref:
          type: string
          nullable: true
        supply_point_ref:
          type: string
          nullable: true
        commodity:
          $ref: "#/components/schemas/EnergyNullableCommodity"
        currency:
          $ref: "#/components/schemas/EnergyNullableCurrency"
        net_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        tax_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        gross_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        advance_payments_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        other_payments_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        adjustments:
          type: array
          items:
            $ref: "#/components/schemas/EnergySettlementAdjustment"
        balance_kind:
          type: string
          nullable: true
          enum: [amount_due, credit, settled]
        balance_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        payment_due_date:
          type: string
          format: date
          nullable: true
        disposition:
          $ref: "#/components/schemas/EnergyPaymentDisposition"
        installment_plans:
          type: array
          items:
            $ref: "#/components/schemas/EnergyInstallmentPlan"
    EnergySettlementAdjustment:
      type: object
      additionalProperties: false
      required: [ref, settlement_ref, kind, description, amount, effect, application]
      properties:
        ref:
          type: string
        settlement_ref:
          type: string
        kind:
          type: string
          nullable: true
          enum: [relief, discount, rebate, fee, surcharge, correction, other]
        description:
          type: string
          nullable: true
        amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        effect:
          type: string
          nullable: true
          enum: [increases_cost, decreases_cost]
        application:
          type: string
          nullable: true
          enum: [included_in_gross_amount, applied_after_gross_amount]
    EnergyPaymentDisposition:
      type: object
      additionalProperties: false
      required: [ref, settlement_ref, action, payment_method, status, date, payment_account_ref, payment_reference, mandate_reference, creditor_identifier]
      properties:
        ref:
          type: string
          example: payment_disposition_1
        settlement_ref:
          type: string
          example: settlement_1
        action:
          type: string
          nullable: true
          enum: [payment_due, refund, carry_forward, bank_details_required, none]
        payment_method:
          type: string
          nullable: true
          enum: [direct_debit, bank_transfer, cash, card, other]
        status:
          type: string
          nullable: true
          enum: [requested, scheduled, completed, cancelled, other]
        date:
          type: string
          format: date
          nullable: true
        payment_account_ref:
          type: string
          nullable: true
        payment_reference:
          type: string
          nullable: true
        mandate_reference:
          type: string
          nullable: true
        creditor_identifier:
          type: string
          nullable: true
    EnergyInstallmentPlan:
      type: object
      additionalProperties: false
      required: [ref, settlement_ref, gross_amount, net_amount, tax_amount, frequency, first_due_date, last_due_date, installment_count, schedule]
      properties:
        ref:
          type: string
          example: installment_plan_1
        settlement_ref:
          type: string
          example: settlement_1
        gross_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        net_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        tax_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        frequency:
          type: string
          nullable: true
          enum: [monthly, quarterly, annual, irregular, one_time, other]
        first_due_date:
          type: string
          format: date
          nullable: true
        last_due_date:
          type: string
          format: date
          nullable: true
        installment_count:
          type: integer
          nullable: true
          minimum: 1
        schedule:
          type: array
          items:
            $ref: "#/components/schemas/EnergyInstallment"
    EnergyInstallment:
      type: object
      additionalProperties: false
      required: [ref, installment_plan_ref, due_date, gross_amount, net_amount, tax_amount, status]
      properties:
        ref:
          type: string
        installment_plan_ref:
          type: string
        due_date:
          type: string
          format: date
          nullable: true
        gross_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        net_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        tax_amount:
          $ref: "#/components/schemas/EnergyNullableAmount"
        status:
          type: string
          nullable: true
          enum: [planned, due, paid, cancelled, other]
    EnergyPaymentAccount:
      type: object
      additionalProperties: false
      required: [ref, scope_type, scope_ref, supply_point_ref, settlement_ref, role, account_holder, iban, bic, bank_name]
      properties:
        ref:
          type: string
          example: payment_account_1
        scope_type:
          type: string
          enum: [document, supply_point, settlement]
        scope_ref:
          type: string
          nullable: true
        supply_point_ref:
          type: string
          nullable: true
        settlement_ref:
          type: string
          nullable: true
        role:
          type: string
          nullable: true
          enum: [supplier_collection_account, customer_refund_account, customer_direct_debit_account, other]
        account_holder:
          type: string
          nullable: true
        iban:
          type: string
          nullable: true
          description: IBAN in normalized uppercase form when visible and valid.
        bic:
          type: string
          nullable: true
          pattern: '^[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?$'
        bank_name:
          type: string
          nullable: true
    EnergyMeterScopeType:
      type: string
      enum: [supply_point, metering_location, meter_assignment]
    EnergyNullableCommodity:
      type: string
      nullable: true
      enum: [electricity, natural_gas, other]
    EnergyNullableUnit:
      type: string
      nullable: true
      enum: [Wh, kWh, MWh, varh, kvarh, Mvarh, W, kW, MW, m3, day, month, year, item, other]
    EnergyNullableDecimal:
      type: string
      nullable: true
      pattern: '^\d+(?:\.\d+)?$'
      example: "18432.000"
    EnergyNullableAmount:
      type: string
      nullable: true
      pattern: '^\d+\.\d{2}$'
      example: "418.27"
    EnergyNullableSignedAmount:
      type: string
      nullable: true
      pattern: '^-?\d+\.\d{2}$'
    EnergyNullableTaxRate:
      type: string
      nullable: true
      pattern: '^\d+\.\d{2}$'
      example: "19.00"
    EnergyNullableCurrency:
      type: string
      nullable: true
      pattern: '^[A-Z]{3}$'
      example: EUR
    ProfileSourceComponent:
      type: object
      additionalProperties: true
      description: Profile-defined source component used to bind normalized values and citations to physical pages from the immutable extraction run. Known fields are shared across profiles, while a versioned profile can add its own component metadata.
      properties:
        ref:
          type: string
          example: primary_invoice
        kind:
          type: string
          example: primary_invoice
        physical_pages:
          type: array
          items:
            type: integer
            minimum: 1
          example: [1, 2]
        precedence:
          type: integer
          minimum: 1
          example: 1
    EnergySourceComponent:
      type: object
      additionalProperties: false
      required: [ref, kind, physical_pages, precedence]
      properties:
        ref:
          type: string
          example: primary_invoice
        kind:
          type: string
          enum: [primary_invoice, invoice_detail, portal_snapshot, annex, form, annotation, unknown]
        physical_pages:
          type: array
          items:
            type: integer
            minimum: 1
          example: [1, 2]
        precedence:
          type: integer
          minimum: 1
          example: 1
    EnergyFieldStatus:
      type: string
      enum: [verified, needs_review, missing, redacted]
    EnergyFieldQuality:
      type: object
      additionalProperties: false
      required: [entity_ref, field, json_pointer, status, signals]
      properties:
        entity_ref:
          type: string
          example: relationship_1
        field:
          type: string
          example: customer_number
          description: Profile-defined quality or review target. It usually names a direct property, but composite targets such as billing_period summarize multiple payload properties. Do not derive a payload path from this value; use json_pointer only when non-null.
        json_pointer:
          type: string
          nullable: true
          description: Exact path within the versioned payload when the profile can identify one; null for composite or otherwise non-addressable targets.
        status:
          $ref: "#/components/schemas/EnergyFieldStatus"
        signals:
          type: array
          items:
            type: string
          example: [ocr_character_ambiguity]
        evidence:
          type: array
          description: Present only when the profile result is requested with `include=evidence`.
          items:
            $ref: "#/components/schemas/EnergyEvidence"
    EnergyEvidence:
      type: object
      additionalProperties: false
      required: [component_ref, physical_page, printed_page, label, text, source, match, bbox]
      properties:
        component_ref:
          type: string
          example: primary_invoice
        physical_page:
          type: integer
          minimum: 1
          example: 1
        printed_page:
          type: string
          nullable: true
          example: "1"
        label:
          type: string
          nullable: true
          example: Kundennummer
        text:
          type: string
          example: KUNDE-1O
        source:
          type: string
          enum: [native_text, embedded_ocr, tesseract_ocr, combined]
        match:
          type: string
          enum: [exact, normalized, manual]
        reviewer_transcribed:
          type: boolean
          description: True when evidence text was supplied by an authorized reviewer as a manual transcription rather than copied from machine OCR.
        bbox:
          oneOf:
            - $ref: "#/components/schemas/EnergyEvidenceBoundingBox"
            - $ref: "#/components/schemas/ProfileNullValue"
    EnergyEvidenceBoundingBox:
      type: object
      additionalProperties: false
      required: [x, y, width, height]
      properties:
        x:
          type: number
          format: float
          minimum: 0
        y:
          type: number
          format: float
          minimum: 0
        width:
          type: number
          format: float
          minimum: 0
        height:
          type: number
          format: float
          minimum: 0
    ProfileEvidenceBoundingBox:
      type: object
      additionalProperties: false
      description: Optional profile-neutral coordinates for a citation inside its physical page artifact.
      required: [x, y, width, height]
      properties:
        x:
          type: number
          format: float
          minimum: 0
        y:
          type: number
          format: float
          minimum: 0
        width:
          type: number
          format: float
          minimum: 0
        height:
          type: number
          format: float
          minimum: 0
    ProfileEvidence:
      type: object
      additionalProperties: true
      description: Profile-defined field evidence. Known page and provenance fields are shared across profiles; a versioned profile can add fields without changing the common response envelope.
      properties:
        invoice_ref:
          type: string
          description: Owning invoice for flattened evidence from a packet-shaped profile result.
        entity_ref:
          type: string
          description: Stable profile entity supported by this citation.
        field:
          type: string
          description: Profile field supported by this citation.
        field_status:
          type: string
          example: verified
        component_ref:
          type: string
          example: primary_invoice
        physical_page:
          type: integer
          minimum: 1
          example: 1
        printed_page:
          type: string
          nullable: true
          example: "1"
        label:
          type: string
          nullable: true
        text:
          type: string
        source:
          type: string
          minLength: 1
          maxLength: 64
          pattern: "^[a-z][a-z0-9_]*$"
          example: native_text
          description: Profile-defined provenance identifier validated by the selected profile against the recorded extraction run.
        match:
          type: string
          enum: [exact, normalized, manual]
        reviewer_transcribed:
          type: boolean
        bbox:
          oneOf:
            - $ref: "#/components/schemas/ProfileEvidenceBoundingBox"
            - $ref: "#/components/schemas/ProfileNullValue"
    ProfileValidationSummary:
      type: object
      description: Versioned diagnostic snapshot produced by profile validation. After a review, top-level effective outcome, handoff status, reason arrays, warnings, and the current profile payload's field-quality rows are authoritative; machine-time values such as `field_status_counts` or the nested handoff status can remain unchanged. German energy field quality is under `effective_payload.invoices[].data.field_quality`. Profiles can add diagnostic properties in later versions.
      properties:
        outcome_reason:
          type: string
          nullable: true
        machine_review_reasons:
          type: array
          description: Review reasons captured from machine validation before any human decision.
          items:
            type: string
        structural_review_reasons:
          type: array
          description: Packet and grouping blockers such as `document_structure_ambiguous` or `mixed_commodity_scope_ambiguous`.
          items:
            type: string
        packet_review_reasons:
          type: array
          description: Packet-boundary and page-accounting blockers for packet-shaped profile results.
          items:
            type: string
        unassigned_physical_pages:
          type: array
          description: Sorted physical pages not owned by a returned invoice.
          items:
            type: integer
            minimum: 1
        invoice_count:
          type: integer
          minimum: 0
          description: Number of independently issued invoices returned in the packet.
        invoices:
          type: array
          description: Compact invoice-local outcomes and validation snapshots for packet-shaped profile results.
          items:
            $ref: "#/components/schemas/GermanEnergyInvoiceValidationRollup"
        document_kind:
          type: string
        supply_point_count:
          type: integer
          minimum: 0
        field_status_counts:
          type: object
          description: Machine-time field-quality counts. These are diagnostic and are not recalculated after every review decision.
          additionalProperties:
            type: integer
        handoff_projection:
          type: string
          example: de.energy.prior-supplier-overview@1
        handoff_status:
          allOf:
            - $ref: "#/components/schemas/ProfileHandoffStatus"
          description: Handoff state captured by validation. Use the result envelope's top-level `handoff_status` for the authoritative current state.
        handoff_review_reasons:
          type: array
          items:
            type: string
        full_invoice_checks:
          $ref: "#/components/schemas/EnergyFullInvoiceChecks"
        valid:
          type: boolean
          description: Present after a review decision; true when the effective profile outcome is accepted.
        reviewed:
          type: boolean
          description: Present with value true after at least one review decision.
        review_reasons:
          type: array
          description: Current profile-level review reasons after a review decision. Structural reasons such as `document_structure_ambiguous` and `mixed_commodity_scope_ambiguous` keep the packet in review and prevent downstream handoff.
          items:
            type: string
        warnings:
          type: array
          description: Effective warnings copied into review diagnostics after a decision.
          items:
            type: string
        failure_code:
          type: string
          description: Profile failure code when no finalized usable profile payload exists, including when finalization fails after provisional result persistence.
      additionalProperties: true
    GermanEnergyInvoiceValidationRollup:
      type: object
      additionalProperties: false
      description: Invoice-local state embedded in the packet validation summary.
      required: [invoice_ref, machine_outcome, effective_outcome, handoff_status, validation_summary]
      properties:
        invoice_ref:
          type: string
        machine_outcome:
          $ref: "#/components/schemas/ProfileMachineOutcome"
        effective_outcome:
          $ref: "#/components/schemas/ProfileEffectiveOutcome"
        handoff_status:
          $ref: "#/components/schemas/ProfileHandoffStatus"
        validation_summary:
          type: object
          additionalProperties: true
          description: Complete invoice-local field, structure, reconciliation, and handoff diagnostics.
    EnergyFullInvoiceChecks:
      type: object
      additionalProperties: false
      description: Deterministic German energy full-invoice profile diagnostics for reference links, typed values, date ranges, natural-gas conversion arithmetic, and invoice monetary reconciliation. Failed checks contribute stable review reasons; use the result's top-level outcome and reason arrays for workflow decisions.
      required: [referential_integrity, value_validation, date_ranges, gas_reconciliations, monetary_reconciliations]
      properties:
        referential_integrity:
          type: object
          additionalProperties: true
          description: Reports duplicate or unresolved refs, missing scope refs, and links whose document, supply-point, settlement, commodity, or currency ownership is inconsistent.
        value_validation:
          type: array
          description: Path-level validation for amounts, decimals, dates, installment counts, IBANs, and BICs.
          items:
            type: object
            additionalProperties: true
        date_ranges:
          type: array
          description: Checks that each applicable start date is not after its end date.
          items:
            type: object
            additionalProperties: true
        gas_reconciliations:
          type: array
          description: Reconciles volume × condition number × calorific value with the reported energy quantity using source-precision tolerance.
          items:
            type: object
            additionalProperties: true
        monetary_reconciliations:
          type: array
          description: Checks net-plus-tax totals, tax-rate calculations, settlement balances, installment arithmetic, and settlement tax totals.
          items:
            type: object
            additionalProperties: true
    ProfileReviewDecisionRequest:
      oneOf:
        - type: object
          additionalProperties: false
          required: [action, invoice_ref, entity_ref, field]
          properties:
            action:
              type: string
              enum: [confirm]
            invoice_ref:
              type: string
              minLength: 1
              maxLength: 160
              example: invoice_5f2db86e322d058b2bfd
              description: Identifies the exact `effective_payload.invoices[]` item containing the reviewed German energy field.
            entity_ref:
              type: string
              minLength: 1
              maxLength: 160
              example: relationship_1
            field:
              type: string
              minLength: 1
              maxLength: 120
              example: customer_number
            reason:
              type: string
              nullable: true
              maxLength: 2000
            review_duration_seconds:
              type: integer
              nullable: true
              minimum: 1
              maximum: 86400
              example: 95
              description: Optional caller-supplied workflow telemetry containing measured active human-review time spent reaching this decision. This is not processing wait time or wall-clock elapsed time. Omission or null leaves duration coverage incomplete and is never treated as zero.
            evidence_reference:
              $ref: "#/components/schemas/ProfileReviewEvidenceReference"
        - type: object
          additionalProperties: false
          required: [action, invoice_ref, entity_ref, field, corrected_value, evidence_reference]
          properties:
            action:
              type: string
              enum: [correct]
            invoice_ref:
              type: string
              minLength: 1
              maxLength: 160
              example: invoice_5f2db86e322d058b2bfd
              description: Identifies the exact `effective_payload.invoices[]` item containing the reviewed German energy field.
            entity_ref:
              type: string
              minLength: 1
              maxLength: 160
              example: relationship_1
            field:
              type: string
              minLength: 1
              maxLength: 120
              example: customer_number
            corrected_value:
              anyOf:
                - type: string
                  minLength: 1
                  maxLength: 4000
                - $ref: "#/components/schemas/ProfileReviewBillingPeriodCorrection"
                - $ref: "#/components/schemas/ProfileReviewAddressCorrection"
                - type: number
                - type: boolean
                - type: array
                  items: {}
                - type: object
                  additionalProperties: true
              description: Non-empty profile-defined corrected JSON value for the selected field. The selected profile validates its exact type and semantics. Named branches preserve generated types for the current German energy profile, which uses strings for most fields, `ProfileReviewBillingPeriodCorrection` for `billing_period`, and `ProfileReviewAddressCorrection` for `service_address` and `billing_address`; the remaining branches keep the endpoint extensible for future profile modules. Identifier and date corrections are normalized and validated before the decision is stored. Every populated German energy address component must occur in the corrected raw address and supporting evidence.
            reason:
              type: string
              nullable: true
              maxLength: 2000
            review_duration_seconds:
              type: integer
              nullable: true
              minimum: 1
              maximum: 86400
              example: 95
              description: Optional caller-supplied workflow telemetry containing measured active human-review time spent reaching this decision. This is not processing wait time or wall-clock elapsed time. Omission or null leaves duration coverage incomplete and is never treated as zero.
            evidence_reference:
              allOf:
                - $ref: "#/components/schemas/ProfileReviewEvidenceReference"
              description: Fresh page evidence whose text supports the corrected value. Identifier, party, and address corrections require a matching label or role in the evidence text. The component, physical page, and source must exist in the recorded page manifest. The text is accepted as a privileged reviewer transcription and is not compared with OCR or native extracted text. It is stored with match `manual` and `reviewer_transcribed=true`; existing machine evidence is not reused as correction evidence.
        - type: object
          additionalProperties: false
          required: [action, reason]
          description: Rejects the complete profile result. German energy packet rejection must omit `invoice_ref` because rejection is not invoice-scoped.
          properties:
            action:
              type: string
              enum: [reject]
            reason:
              type: string
              minLength: 1
              maxLength: 2000
              example: The uploaded PDF is not the requested customer invoice.
            review_duration_seconds:
              type: integer
              nullable: true
              minimum: 1
              maximum: 86400
              example: 95
              description: Optional caller-supplied workflow telemetry containing measured active human-review time spent reaching this decision. This is not processing wait time or wall-clock elapsed time. Omission or null leaves duration coverage incomplete and is never treated as zero.
    ProfileReviewBillingPeriodCorrection:
      type: object
      additionalProperties: false
      required: [start, end]
      properties:
        start:
          type: string
          format: date
          example: "2024-01-01"
        end:
          type: string
          format: date
          example: "2024-12-31"
      description: Billing period with start on or before end.
    ProfileReviewAddressCorrection:
      type: object
      additionalProperties: false
      required: [raw]
      properties:
        raw:
          type: string
          minLength: 1
          maxLength: 4000
          example: Musterstraße 14, 70173 Stuttgart
        street:
          type: string
          nullable: true
        house_number:
          type: string
          nullable: true
        postal_code:
          type: string
          nullable: true
        city:
          type: string
          nullable: true
        country_code:
          type: string
          nullable: true
          pattern: '^[A-Z]{2}$'
          example: DE
      description: Structured service or billing address. Every populated component must occur in raw and in the supporting evidence; country_code must be a valid ISO-3166 alpha-2 code visible in the evidence.
    ProfileReviewEvidenceReference:
      type: object
      additionalProperties: false
      required: [component_ref, physical_page, text, source]
      properties:
        component_ref:
          type: string
          minLength: 1
          maxLength: 160
          example: primary_invoice
        physical_page:
          type: integer
          minimum: 1
          example: 1
        printed_page:
          type: string
          nullable: true
          maxLength: 40
          example: "1"
        label:
          type: string
          nullable: true
          maxLength: 255
          example: Kundennummer
          description: Printed label or role used by the selected profile to validate that the citation supports the reviewed field.
        text:
          type: string
          minLength: 1
          maxLength: 4000
          example: KUNDE-10
          description: Complete supporting text transcribed by an authorized reviewer. exdata verifies the recorded component, physical page, and source but does not compare this transcription with OCR or native extracted text.
        source:
          type: string
          minLength: 1
          maxLength: 64
          pattern: "^[a-z][a-z0-9_]*$"
          example: native_text
          description: Profile-defined source that the selected profile reviewer validates against the recorded extraction run.
        match:
          type: string
          enum: [exact, normalized, manual]
          default: manual
        bbox:
          oneOf:
            - $ref: "#/components/schemas/ProfileEvidenceBoundingBox"
            - $ref: "#/components/schemas/ProfileNullValue"
    ProfileReviewDecisionApplication:
      type: object
      required: [data]
      properties:
        data:
          anyOf:
            - type: object
              description: Full response for a user session or an API token with both `extractions:review` and `documents:read`.
              required: [decision, sector_extraction]
              properties:
                decision:
                  $ref: "#/components/schemas/ProfileReviewDecision"
                sector_extraction:
                  $ref: "#/components/schemas/SectorExtraction"
            - type: object
              description: Metadata-only response for an API token with `extractions:review` but without `documents:read`.
              required: [decision, sector_extraction]
              properties:
                decision:
                  $ref: "#/components/schemas/ProfileReviewOnlyDecision"
                sector_extraction:
                  $ref: "#/components/schemas/ProfileReviewOnlyResult"
    ProfileReviewOnlyDecision:
      type: object
      required: [id, action, invoice_ref, entity_ref, field, review_duration_seconds, resulting_effective_outcome, resulting_handoff_status, expected_lock_version, resulting_lock_version, created_at]
      properties:
        id:
          type: integer
        action:
          type: string
          enum: [confirm, correct, reject]
        invoice_ref:
          type: string
          nullable: true
          description: Reviewed invoice for an invoice-scoped field decision; null for complete-result rejection or profiles without invoice-scoped review.
        entity_ref:
          type: string
          nullable: true
        field:
          type: string
          nullable: true
        review_duration_seconds:
          type: integer
          nullable: true
          minimum: 1
          maximum: 86400
          description: Caller-supplied workflow telemetry containing measured active human-review time for this decision, or null when it was not measured. It is not wall-clock elapsed time and null is not zero.
        resulting_effective_outcome:
          $ref: "#/components/schemas/ProfileEffectiveOutcome"
        resulting_handoff_status:
          $ref: "#/components/schemas/ProfileHandoffStatus"
        expected_lock_version:
          type: integer
          minimum: 0
        resulting_lock_version:
          type: integer
          minimum: 1
        created_at:
          type: string
          format: date-time
          nullable: true
    ProfileReviewOnlyResult:
      type: object
      required: [id, document_id, profile, profile_version, schema_version, effective_outcome, handoff_status, lock_version, etag, acceptance_source, reviewed_at]
      properties:
        id:
          type: integer
        document_id:
          type: integer
        profile:
          type: string
        profile_version:
          type: string
        schema_version:
          type: string
        effective_outcome:
          $ref: "#/components/schemas/ProfileEffectiveOutcome"
        handoff_status:
          $ref: "#/components/schemas/ProfileHandoffStatus"
        lock_version:
          type: integer
          minimum: 0
        etag:
          type: string
          example: '"extraction-result-789-v1"'
        acceptance_source:
          type: string
          nullable: true
        reviewed_at:
          type: string
          format: date-time
          nullable: true
    ProfileReviewDecision:
      type: object
      required: [id, action, invoice_ref, entity_ref, field, reason, previous_value, corrected_value, evidence_reference, review_duration_seconds, reviewer_user_id, account_api_token_id, previous_effective_outcome, resulting_effective_outcome, previous_handoff_status, resulting_handoff_status, expected_lock_version, resulting_lock_version, idempotency_key_prefix, created_at]
      properties:
        id:
          type: integer
        action:
          type: string
          enum: [confirm, correct, reject]
        invoice_ref:
          type: string
          nullable: true
          description: Reviewed invoice for an invoice-scoped field decision; null for complete-result rejection or profiles without invoice-scoped review.
        entity_ref:
          type: string
          nullable: true
        field:
          type: string
          nullable: true
        reason:
          type: string
          nullable: true
        previous_value:
          nullable: true
        corrected_value:
          nullable: true
        evidence_reference:
          oneOf:
            - $ref: "#/components/schemas/ProfileEvidence"
            - $ref: "#/components/schemas/ProfileNullValue"
        review_duration_seconds:
          type: integer
          nullable: true
          minimum: 1
          maximum: 86400
          description: Caller-supplied workflow telemetry containing measured active human-review time for this decision, or null when it was not measured. It is not processing wait time or wall-clock elapsed time and null is not zero.
        reviewer_user_id:
          type: integer
          nullable: true
        account_api_token_id:
          type: integer
          nullable: true
        previous_effective_outcome:
          $ref: "#/components/schemas/ProfileEffectiveOutcome"
        resulting_effective_outcome:
          $ref: "#/components/schemas/ProfileEffectiveOutcome"
        previous_handoff_status:
          $ref: "#/components/schemas/ProfileHandoffStatus"
        resulting_handoff_status:
          $ref: "#/components/schemas/ProfileHandoffStatus"
        expected_lock_version:
          type: integer
          minimum: 0
        resulting_lock_version:
          type: integer
          minimum: 1
        idempotency_key_prefix:
          type: string
        created_at:
          type: string
          format: date-time
          nullable: true
    ProfileReviewConflictError:
      allOf:
        - $ref: "#/components/schemas/ErrorEnvelope"
        - type: object
          properties:
            expected_lock_version:
              type: integer
              minimum: 0
            current_lock_version:
              type: integer
              minimum: 0
            conflict_reason:
              type: string
              enum: [payload_mismatch]

    Preview:
      type: object
      properties:
        id:
          type: integer
        filename:
          type: string
        file_format:
          type: string
        file_size:
          type: integer
        preview:
          type: string
          format: uri
    Extractions:
      type: object
      description: >
        Text values and candidates use UTF-8. Legacy single-byte text is converted to UTF-8;
        valid Unicode text is preserved, including text within structured fields.
        Extraction fields keyed by normalized field name. Missing or uncertain
        values are represented as JSON null, not placeholder strings. Standard
        keys include
        type, title, date, issue_date, email_date, payment_due_date, period_start, period_end,
        document_number, customer_id, contract_id, order_id, reference_id,
        payment_reference, payment_status, currency,
        net_amount, gross_amount, opening_balance, closing_balance, tax_amount,
        tax_rate, tax_breakdowns, tax_system, taxability, tax_collection_mechanism,
        cross_border_tax_treatment, supply_type,
        tax_exemption_reason, account_holder, iban, bic, bank, sender_name,
        sender_street, sender_zip, sender_city, sender_state,
        sender_country_code, sender_tax_id, sender_vat_number, recipient_name,
        recipient_street, recipient_zip, recipient_city, recipient_state,
        recipient_country_code, recipient_tax_id,
        recipient_vat_number, email, phone_number, website, company_register_id,
        cost_center, note, from, from_email, to,
        to_email, subject, message_id, and in_reply_to. For an email without a
        usable financial attachment, `date` comes from the email header. When
        an attachment is selected, document `date` and
        `issue_date` remain attachment-authoritative while `email_date` keeps
        the envelope date. When present, `tax_system` is `vat`, `gst`, or
        `sales_tax`; missing or uncertain values are null. Custom extraction
        fields can add additional keys. Standard XRechnung 3.0 invoices in UBL
        and CII syntax, Extension XRechnung 3.0 in UBL and CII syntax, and CVD
        XRechnung 0.9 in CII syntax are validated in their original syntax with
        the matching pinned KoSIT scenario before accepted values become
        authoritative. Standard and Extension XRechnung report
        xml_profile_conformance; CVD CII reports structural_and_business. UBL
        CVD is not claimed as supported. For UBL invoices
        declaring the exact Extension XRechnung 3.0 profile, exdata validates
        the original UBL and
        maps applicable document-level values into the v1 keys:
        type, document_number, date, issue_date, period_start, period_end,
        currency, net_amount, gross_amount, tax_amount, sender and recipient
        identity/address/tax fields, customer_id, payment_due_date, one
        unambiguous payee iban and bic, tax breakdown/classification fields, and
        note. Recursive line hierarchy, embedded attachment metadata, and
        third-party payment rows feed the generated HTML visualization but are
        not returned as v1 extraction fields; exceptionally large line sets or
        repeatable review sections are shown as clearly labelled source-order
        prefixes. Multiple ambiguous
        payee accounts remain validation-only and leave the singular iban and
        bic fields null.
        For this profile, gross_amount is UBL TaxInclusiveAmount (BT-112), not
        PayableAmount after prepaid or third-party payment allocation. Invalid
        invoices and unknown or unsupported profiles fail closed. For invoices
        declaring the exact ZUGFeRD 1.0 COMFORT profile, exdata validates the
        original XML against its XSD, Schematron constraints, and
        arithmetic rules, then maps the applicable document, party, payment,
        amount, tax, billing-period, and note values into the same v1 keys.
        This path reports structural_and_business without claiming complete XML
        profile conformance.
        Support is bounded to invoices with TypeCode 380 or 84 and the
        published tax TypeCodes VAT, ZF_INSURANCE_TAX (insurance tax), or AAJ
        (second-hand-parts tax).
        gross_amount is GrandTotalAmount, not the optional DuePayableAmount.
        ZUGFeRD 1.0 BASIC and EXTENDED remain unsupported; other document or
        tax codes fail closed.
      x-field-enums:
        tax_system:
          - vat
          - gst
          - sales_tax
      additionalProperties:
        $ref: "#/components/schemas/ExtractionField"
      example:
        type:
          value: invoice
          candidates: [invoice]
        document_number:
          value: RE-2026-1048
          candidates: [RE-2026-1048]
          provenance:
            method: structured_invoice
            source: pdf_embedded_xml
            derived_from: []
            transforms: []
        gross_amount:
          value: "1284.60"
          candidates: ["1.284,60 EUR", "EUR 1,284.60"]
        tax_breakdowns:
          value:
            - taxable_amount: "1079.50"
              tax_amount: "205.10"
              tax_rate: "19.00"
              taxability: taxable
              tax_collection_mechanism: seller_collected
              tax_exemption_reason: null
          candidates: ["VAT 19% 205.10"]
    NullableExtractions:
      type: object
      nullable: true
      description: >
        Extraction fields keyed by normalized field name, or null while an
        extraction-mode document has not completed.
      additionalProperties:
        $ref: "#/components/schemas/ExtractionField"
    ExtractionField:
      type: object
      required: [value, candidates]
      properties:
        value:
          description: >
            Normalized extracted value. Most fields use strings or null. Amounts
            are dot-decimal strings with two digits, dates use YYYY-MM-DD,
            currency uses ISO 4217, and tax_breakdowns uses an array of
            TaxBreakdown rows.
          oneOf:
            - type: string
              nullable: true
            - type: array
              items:
                $ref: "#/components/schemas/TaxBreakdown"
            - type: object
        candidates:
          type: array
          nullable: true
          description: Raw or derived candidate values considered for this field. The field-level `provenance` describes only the selected `value`, not every candidate.
          items: {}
        provenance:
          $ref: "#/components/schemas/ExtractionFieldProvenance"
    ExtractionFieldProvenance:
      type: object
      nullable: true
      additionalProperties: false
      description: Persisted origin of the selected field value. Null on legacy rows, for a null field value, or on all effective extraction fields projected from a profile result after any human-review decision, including fields not individually reviewed, because that projection no longer represents untouched automatic output. This object contains identifiers only, never document values, snippets, or validator message text.
      required: [method, source, derived_from, transforms]
      properties:
        method:
          type: string
          enum: [structured_invoice, ai, deterministic, structured_markup, email_envelope, derived, unknown]
          description: Mechanism that produced the selected value. Normalization preserves the originating method; `derived` is reserved for a semantic value computed from other fields.
        source:
          type: string
          nullable: true
          enum: [xml, pdf_embedded_xml, email_attachment_xml, document_text, pdf_text, ocr_text, document_file, document_markup, email_header, email_body, email_attachment, caller_context, mixed, unknown]
          description: Bounded source category for the selected value. `document_text` or `mixed` is used when field-accurate native-text versus OCR attribution is unavailable.
        derived_from:
          type: array
          uniqueItems: true
          maxItems: 100
          description: Normalized field names or JSON-pointer-like identifiers used to derive the selected value; document values are never included.
          items:
            type: string
            maxLength: 128
            pattern: '^[a-z][a-z0-9_.-]{0,127}$'
        transforms:
          type: array
          uniqueItems: true
          maxItems: 100
          description: Bounded transform identifiers applied while producing or normalizing the selected value.
          items:
            type: string
            maxLength: 128
            pattern: '^[a-z][a-z0-9_.-]{0,127}$'
    TaxBreakdown:
      type: object
      description: One visible tax rate or tax category from the document.
      properties:
        taxable_amount:
          type: string
          nullable: true
          pattern: '^-?[0-9]+(\.[0-9]{2})$'
          example: "1079.50"
        tax_amount:
          type: string
          nullable: true
          pattern: '^-?[0-9]+(\.[0-9]{2})$'
          example: "205.10"
        tax_rate:
          type: string
          nullable: true
          pattern: '^-?[0-9]+(\.[0-9]{2})$'
          example: "19.00"
        taxability:
          type: string
          nullable: true
          enum: [taxable, zero_rated, exempt, out_of_scope]
        tax_collection_mechanism:
          type: string
          nullable: true
          enum: [seller_collected, reverse_charge, buyer_use_tax, not_collected]
        tax_exemption_reason:
          type: string
          nullable: true
          description: Visible exemption, zero-rating, out-of-scope, or reverse-charge reason.
    InsufficientCreditsError:
      allOf:
        - $ref: "#/components/schemas/ErrorEnvelope"
        - type: object
          required: [available_credits, required_credits, document]
          properties:
            available_credits:
              type: integer
              description: Credits or committed units currently available for this upload.
              example: 0
            required_credits:
              type: integer
              description: Billable units required for the upload.
              example: 1
            document:
              $ref: "#/components/schemas/Document"
    TestModeLimitError:
      allOf:
        - $ref: "#/components/schemas/ErrorEnvelope"
        - type: object
          required: [account_daily_document_limit, user_daily_document_limit, token_daily_document_limit, retry_after]
          properties:
            account_daily_document_limit:
              type: integer
              example: 25
            user_daily_document_limit:
              type: integer
              example: 50
            token_daily_document_limit:
              type: integer
              example: 10
            retry_after:
              type: integer
              minimum: 1
              description: Number of seconds until the next sandbox daily window. This matches the `Retry-After` response header.
              example: 21600
