{
  "openapi": "3.0.0",
  "info": {
    "title": "Artos API",
    "description": "API for document generation, template management, and document organization",
    "version": "1.0.0",
    "contact": {
      "name": "Artos Support",
      "email": "internal@artosai.com"
    }
  },
  "servers": [
    {
      "url": "https://api.artosai.com",
      "description": "Production server"
    },
    {
      "url": "http://localhost:8000",
      "description": "Local development server"
    }
  ],
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT",
        "description": "Okta access-token JWT sent as a Bearer token. The token identifies the user and scopes access to the user's organization."
      },
      "documentSessionAuth": {
        "type": "http",
        "scheme": "bearer",
        "description": "Short-lived document session token sent in the Authorization header. Do not put this credential in a URL."
      }
    },
    "schemas": {
      "FileObject": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "description": "File name"
          },
          "resource_id": {
            "type": "string",
            "description": "Opaque Artos resource identifier for the file."
          }
        },
        "required": ["name", "resource_id"]
      },
      "DocumentFileSessionRequest": {
        "type": "object",
        "properties": {
          "resource_id": {
            "type": "string",
            "description": "Opaque file, document, or template resource identifier returned by Artos."
          }
        },
        "required": ["resource_id"]
      },
      "DocumentFileSessionResponse": {
        "type": "object",
        "properties": {
          "session_token": {
            "type": "string",
            "description": "Short-lived revocable token for the authenticated document stream."
          }
        },
        "required": ["session_token"]
      },
      "SourceFileRequest": {
        "type": "object",
        "properties": {
          "resource_id": {
            "type": "string",
            "description": "Source-file resource identifier beginning with sourcefile-."
          }
        },
        "required": ["resource_id"]
      },
      "GenerateOnlyOfficeConfigRequest": {
        "type": "object",
        "properties": {
          "resource_id": {
            "type": "string",
            "description": "Opaque file, document, or template resource identifier."
          },
          "mode": {
            "type": "string",
            "enum": ["edit", "readonly"],
            "default": "edit"
          },
          "customization": {
            "type": "object",
            "description": "Optional OnlyOffice customization settings."
          },
          "display_type": {
            "type": "string",
            "enum": ["desktop", "mobile", "embedded"],
            "description": "Optional viewer layout."
          }
        },
        "required": ["resource_id"]
      },
      "GenerateOnlyOfficeConfigResponse": {
        "type": "object",
        "properties": {
          "config": {
            "type": "object",
            "description": "Server-generated OnlyOffice configuration."
          },
          "token": {
            "type": "string",
            "nullable": true,
            "description": "Server-generated OnlyOffice configuration token."
          }
        },
        "required": ["config", "token"]
      },
      "ListFilesResponse": {
        "type": "object",
        "properties": {
          "files": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/FileObject"
            }
          }
        }
      },
      "TaskAcceptedResponse": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string",
            "description": "Status message"
          },
          "task_id": {
            "type": "string",
            "description": "Document ID for polling status"
          }
        },
        "required": ["message", "task_id"]
      },
      "TaskStatusResponse": {
        "type": "object",
        "properties": {
          "task_id": {
            "type": "string",
            "description": "Document ID"
          },
          "status": {
            "type": "string",
            "enum": ["Pending", "Ingesting", "Generating", "Ready", "Failed"],
            "description": "Current processing status"
          },
          "progress": {
            "type": "integer",
            "nullable": true,
            "description": "Progress percentage (reserved for future use)"
          },
          "error": {
            "type": "string",
            "nullable": true,
            "description": "Error message if status is Failed"
          }
        },
        "required": ["task_id", "status"]
      },
      "GetDocumentFromIdResponse": {
        "type": "object",
        "properties": {
          "document": {
            "type": "object",
            "description": "Complete document details with sections and metadata"
          }
        }
      },
      "DocumentSetResponse": {
        "type": "object",
        "properties": {
          "document_set_id": {
            "type": "string",
            "description": "Auto-generated UUID"
          },
          "document_set_name": {
            "type": "string",
            "nullable": true
          },
          "organization_id": {
            "type": "string",
            "nullable": true
          },
          "details": {
            "type": "string",
            "nullable": true
          },
          "documents": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "nullable": true
          },
          "version": {
            "type": "integer",
            "nullable": true,
            "description": "Document set version"
          }
        }
      },
      "GetAllDocumentSetsResponse": {
        "type": "object",
        "properties": {
          "document_sets": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/DocumentSetResponse"
            }
          }
        }
      },
      "CreateDocumentSetRequest": {
        "type": "object",
        "description": "Both `workspace_name` (alias) and `document_set_name` are accepted.",
        "properties": {
          "workspace_name": {
            "type": "string",
            "description": "Name for the new document set (alias: document_set_name)"
          }
        },
        "required": ["workspace_name"]
      },
      "GetOneDocumentSetResponse": {
        "type": "object",
        "properties": {
          "users": {
            "type": "array",
            "items": {
              "type": "object"
            }
          },
          "document_set": {
            "type": "array",
            "items": {
              "type": "object"
            }
          }
        }
      },
      "GenerateDocumentRequest": {
        "type": "object",
        "description": "Field aliases: `connector_data_id` = `document_set_key`, `template_id` = `generic_mrt_id`, `workspace_name` = `document_set_name`. Both the alias and field name are accepted.",
        "properties": {
          "document_type": {
            "type": "string",
            "description": "Type of document to generate (e.g., CSR, Protocol)"
          },
          "file_paths": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "S3 object keys for source documents (e.g., org-id/documents/protocol.pdf)"
          },
          "connector_data_id": {
            "type": "string",
            "description": "Unique key for document set (field name: document_set_key)"
          },
          "workspace_name": {
            "type": "string",
            "description": "Human-readable name for the document set (field name: document_set_name)"
          },
          "template_id": {
            "type": "string",
            "description": "ID of the template to use (field name: generic_mrt_id)"
          },
          "output_name": {
            "type": "string",
            "description": "Name for the generated output file (without .docx extension)"
          },
          "selected_section_ids": {
            "oneOf": [
              {
                "type": "array",
                "items": {
                  "type": "string"
                }
              },
              {
                "type": "array",
                "items": {
                  "type": "object"
                }
              }
            ],
            "nullable": true,
            "description": "Specific section IDs to include (optional)"
          },
          "generic_mrt_outline_full": {
            "type": "object",
            "nullable": true,
            "description": "Full outline structure (optional)"
          },
          "document_instructions": {
            "type": "string",
            "nullable": true,
            "description": "Document-level instructions (optional)"
          },
          "style_guide_id": {
            "type": "string",
            "nullable": true,
            "description": "Style guide ID from the style_guides table (optional)"
          }
        },
        "required": [
          "document_type",
          "file_paths",
          "connector_data_id",
          "workspace_name",
          "template_id",
          "output_name"
        ]
      },
      "TemplateInfo": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "template_name": {
            "type": "string"
          },
          "source_document_name": {
            "type": "string"
          },
          "resource_id": {
            "type": "string",
            "description": "Opaque template resource identifier for document-session requests."
          },
          "detected_document_type": {
            "type": "string"
          },
          "template_id": {
            "type": "string"
          },
          "sections": {
            "type": "array",
            "items": {
              "type": "object"
            },
            "nullable": true
          },
          "status": {
            "type": "string",
            "nullable": true
          },
          "template_file_name": {
            "type": "string",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "nullable": true,
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "nullable": true,
            "format": "date-time"
          }
        }
      },
      "ListAllTemplatesResponse": {
        "type": "object",
        "properties": {
          "templates": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/TemplateInfo"
            }
          }
        }
      },
      "GetOneTemplateResponse": {
        "type": "object",
        "properties": {
          "resource_id": {
            "type": "string",
            "description": "Opaque template resource identifier for document-session requests."
          },
          "document_name": {
            "type": "string"
          },
          "template_file_name": {
            "type": "string"
          },
          "template_type": {
            "type": "string"
          },
          "template_nickname": {
            "type": "string"
          }
        }
      },
      "CreateTemplateSectionRuleRequest": {
        "type": "object",
        "properties": {
          "confidence_score": {
            "type": "number",
            "nullable": true
          },
          "rule_type": {
            "type": "string",
            "nullable": true
          },
          "rule_mode": {
            "type": "string",
            "nullable": true
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "explanation": {
            "type": "string",
            "nullable": true
          },
          "generated_content": {
            "type": "string",
            "nullable": true
          },
          "rule_parameters": {
            "type": "object",
            "nullable": true
          }
        }
      },
      "CreateTemplateSectionRequest": {
        "type": "object",
        "properties": {
          "order_index": {
            "type": "integer",
            "description": "Position in template (0-based)"
          },
          "level": {
            "type": "integer",
            "description": "Nesting level (1=top-level)"
          },
          "section_name": {
            "type": "string",
            "description": "Section title"
          },
          "synopsis": {
            "type": "string",
            "nullable": true,
            "description": "Brief summary"
          },
          "template_instructions": {
            "type": "string",
            "nullable": true,
            "description": "Completion instructions"
          },
          "template_text": {
            "type": "string",
            "nullable": true,
            "description": "Template text content"
          },
          "section_type": {
            "type": "string",
            "nullable": true
          },
          "section_mode": {
            "type": "string",
            "nullable": true
          },
          "is_repeating": {
            "type": "boolean",
            "default": false
          },
          "expansion_type": {
            "type": "string",
            "nullable": true,
            "description": "For repeating sections"
          },
          "data_instructions": {
            "type": "string",
            "nullable": true,
            "description": "Data handling instructions"
          },
          "guidance": {
            "type": "string",
            "nullable": true
          },
          "outline_text": {
            "type": "string",
            "nullable": true
          },
          "allowed_data_rules": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "nullable": true
          },
          "examples": {
            "type": "array",
            "items": {
              "type": "object"
            },
            "nullable": true,
            "description": "JSONB examples"
          },
          "rules": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CreateTemplateSectionRuleRequest"
            },
            "nullable": true
          }
        },
        "required": [
          "order_index",
          "level",
          "section_name"
        ]
      },
      "CreateTemplateRequest": {
        "type": "object",
        "properties": {
          "template_name": {
            "type": "string",
            "description": "Name of template"
          },
          "document_type": {
            "type": "string",
            "description": "Document type (e.g., CSR, IND)"
          },
          "sections": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CreateTemplateSectionRequest"
            },
            "description": "At least one section required"
          },
          "template_s3_uri": {
            "type": "string",
            "nullable": true,
            "description": "S3 object key for template file"
          },
          "template_file_name": {
            "type": "string",
            "nullable": true,
            "description": "Template file name"
          },
          "document_description": {
            "type": "string",
            "nullable": true
          },
          "tags": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "nullable": true
          },
          "users": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "nullable": true,
            "description": "User IDs with access"
          }
        },
        "required": [
          "template_name",
          "document_type",
          "sections"
        ]
      },
      "CreateTemplateResponse": {
        "type": "object",
        "properties": {
          "template_id": {
            "type": "string",
            "description": "UUID of created template"
          },
          "template_name": {
            "type": "string"
          },
          "organization_id": {
            "type": "string"
          },
          "section_count": {
            "type": "integer"
          },
          "rule_count": {
            "type": "integer",
            "description": "Total rules across sections"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "message": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "DeleteTemplateSectionResponse": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string",
            "description": "Success message"
          },
          "deleted_section_id": {
            "type": "string",
            "description": "UUID of deleted section"
          },
          "deleted_count": {
            "type": "integer",
            "default": 1,
            "description": "Total sections deleted (including cascaded children)"
          }
        }
      },
      "AddTemplateSectionRequest": {
        "type": "object",
        "properties": {
          "section_name": {
            "type": "string",
            "description": "Name/title of the section"
          },
          "level": {
            "type": "integer",
            "description": "Nesting level (1=top-level, 2=subsection, etc.)"
          },
          "order_index": {
            "type": "integer",
            "description": "Position of section in the template (0-based)"
          }
        },
        "required": ["section_name", "level", "order_index"]
      },
      "AddTemplateSectionResponse": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string",
            "description": "Success message"
          },
          "section_id": {
            "type": "string",
            "description": "UUID of the created section"
          },
          "template_id": {
            "type": "string",
            "description": "UUID of the parent template"
          },
          "section_name": {
            "type": "string",
            "description": "Name of the created section"
          },
          "level": {
            "type": "integer",
            "description": "Nesting level of the section"
          },
          "order_index": {
            "type": "integer",
            "description": "Position of the section in the template"
          }
        },
        "required": ["message", "section_id", "template_id", "section_name", "level", "order_index"]
      },
      "RenameSectionRequest": {
        "type": "object",
        "properties": {
          "section_name": {
            "type": "string",
            "description": "New name/title for the section (e.g., '2.1 Efficacy Results')"
          }
        },
        "required": ["section_name"]
      },
      "RenameSectionResponse": {
        "type": "object",
        "properties": {
          "section_id": {
            "type": "string",
            "description": "UUID of the renamed section"
          },
          "section_name": {
            "type": "string",
            "description": "Updated section name"
          },
          "message": {
            "type": "string",
            "description": "Success message"
          }
        },
        "required": ["section_id", "section_name", "message"]
      },
      "ReorderSectionsRequest": {
        "type": "object",
        "properties": {
          "sections": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "section_id": {
                  "type": "string"
                },
                "order_index": {
                  "type": "integer"
                },
                "level": {
                  "type": "integer"
                }
              },
              "required": ["section_id", "order_index", "level"]
            },
            "description": "List of {section_id, order_index, level} defining the new order"
          }
        },
        "required": ["sections"]
      },
      "SectionSummary": {
        "type": "object",
        "properties": {
          "section_id": {
            "type": "string"
          },
          "section_name": {
            "type": "string"
          },
          "order_index": {
            "type": "integer"
          },
          "level": {
            "type": "integer"
          }
        }
      },
      "ReorderSectionsResponse": {
        "type": "object",
        "properties": {
          "template_id": {
            "type": "string"
          },
          "sections": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SectionSummary"
            },
            "description": "All sections in their new order with updated names"
          },
          "message": {
            "type": "string",
            "description": "Success message"
          }
        },
        "required": ["template_id", "sections", "message"]
      },
      "UpdateRuleStylesRequest": {
        "type": "object",
        "properties": {
          "style_names": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "nullable": true,
            "description": "List of style names to apply (e.g., ['Heading 2', 'Normal'])"
          },
          "fill": {
            "type": "string",
            "nullable": true,
            "description": "Background fill color hex (e.g., '#FFFF00') or null to remove"
          },
          "color": {
            "type": "string",
            "nullable": true,
            "description": "Text/font color hex (e.g., '#FF0000') or null to remove"
          }
        }
      },
      "UpdateRuleStylesResponse": {
        "type": "object",
        "properties": {
          "rule_id": {
            "type": "string",
            "description": "UUID of the updated rule"
          },
          "styles": {
            "type": "object",
            "description": "Updated styles object"
          },
          "updated": {
            "type": "boolean",
            "default": true,
            "description": "Whether the update was successful"
          }
        },
        "required": ["rule_id", "styles", "updated"]
      },
      "GetOneMRTOutlineResponse": {
        "type": "object",
        "properties": {
          "outline": {
            "type": "object",
            "description": "Complete outline with sections"
          }
        }
      },
      "UpdateOutlineRequest": {
        "type": "object",
        "properties": {
          "document_metadata": {
            "type": "object",
            "description": "Outline metadata"
          },
          "connector_data_id": {
            "type": "string",
            "nullable": true,
            "description": "Data connector ID"
          },
          "endpoint_analysis": {
            "type": "string",
            "nullable": true,
            "description": "Analysis text"
          },
          "rule_type_to_table_like_status": {
            "type": "object",
            "default": {},
            "description": "Rule type mappings"
          },
          "sections": {
            "type": "array",
            "items": {
              "type": "object"
            },
            "description": "Section dictionaries with section_id, title, order_index"
          }
        },
        "required": [
          "sections"
        ]
      },
      "UpdateDocumentDetailsSectionRuleRequest": {
        "type": "object",
        "properties": {
          "confidence_score": {
            "type": "number",
            "nullable": true
          },
          "rule_type": {
            "type": "string",
            "nullable": true
          },
          "rule_mode": {
            "type": "string",
            "nullable": true
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "explanation": {
            "type": "string",
            "nullable": true
          },
          "generated_content": {
            "type": "string",
            "nullable": true
          },
          "rule_parameters": {
            "type": "object",
            "default": {}
          }
        }
      },
      "UpdateDocumentDetailsSectionRequest": {
        "type": "object",
        "properties": {
          "order_index": {
            "type": "integer",
            "description": "Position in document"
          },
          "level": {
            "type": "integer",
            "description": "Nesting level"
          },
          "section_id": {
            "type": "string",
            "nullable": true
          },
          "section_type": {
            "type": "string",
            "nullable": true
          },
          "title": {
            "type": "string",
            "nullable": true
          },
          "synopsis": {
            "type": "string",
            "nullable": true
          },
          "template_instructions": {
            "type": "string",
            "nullable": true
          },
          "template_text": {
            "type": "string",
            "nullable": true
          },
          "additional_details": {
            "type": "object",
            "default": {},
            "description": "JSONB metadata"
          },
          "relevant_chunk_ids": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "default": [],
            "description": "Referenced chunks"
          },
          "relevant_chunk_names": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "default": []
          },
          "rules": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/UpdateDocumentDetailsSectionRuleRequest"
            },
            "default": []
          }
        },
        "required": [
          "order_index",
          "level"
        ]
      },
      "UpdateDocumentDetailsRequest": {
        "type": "object",
        "properties": {
          "docx_url": {
            "type": "string",
            "nullable": true,
            "description": "S3 object key of DOCX file"
          },
          "endpoint_analysis": {
            "type": "string",
            "nullable": true
          },
          "output_name": {
            "type": "string",
            "nullable": true
          },
          "connector_data_id": {
            "type": "string",
            "default": "",
            "description": "Data connector ID"
          },
          "rule_type_to_table_like_status": {
            "type": "object",
            "default": {},
            "description": "Rule type mappings"
          },
          "sections": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/UpdateDocumentDetailsSectionRequest"
            },
            "description": "Sections with nested rules"
          },
          "auto_increment_regeneration": {
            "type": "boolean",
            "default": false,
            "description": "Auto-increment regeneration count"
          }
        },
        "required": [
          "sections"
        ]
      },
      "ErrorResponse": {
        "type": "object",
        "properties": {
          "detail": {
            "type": "string",
            "description": "Error message"
          }
        }
      },
      "GetSectionsForDocumentRequest": {
        "type": "object",
        "required": ["document_id"],
        "properties": {
          "document_id": {
            "type": "string",
            "description": "Unique identifier of the document whose section list is being retrieved"
          }
        }
      },
      "SectionItem": {
        "type": "object",
        "properties": {
          "section_id": {
            "type": "string",
            "description": "Unique identifier of the section (the section title), used as section_id in the sources endpoints"
          },
          "section_title": {
            "type": "string",
            "description": "Human-readable display name of the section"
          },
          "section_order": {
            "type": "integer",
            "description": "Zero-based index representing the section's position within the document"
          }
        },
        "required": ["section_id", "section_title", "section_order"]
      },
      "GetSectionsForDocumentResponse": {
        "type": "object",
        "properties": {
          "sections": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SectionItem"
            },
            "description": "Array of section objects sorted by document order"
          }
        }
      }
    }
  },
  "security": [
    {
      "bearerAuth": []
    }
  ],
  "paths": {
    "/document-file-session": {
      "post": {
        "tags": ["Files"],
        "summary": "Create Document File Session",
        "description": "Authorize an opaque resource ID and create a short-lived revocable session token for viewing the file. No S3 URL is returned.",
        "operationId": "createDocumentFileSession",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/DocumentFileSessionRequest"
              },
              "example": {
                "resource_id": "sourcefile-org-id/documents/protocol.pdf"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Session created",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentFileSessionResponse"
                }
              }
            }
          },
          "401": {
            "description": "Missing, invalid, or unauthorized Bearer token"
          },
          "500": {
            "description": "Document session service is unavailable"
          }
        }
      }
    },
    "/source-file": {
      "post": {
        "tags": ["Files"],
        "summary": "Stream an Authorized Source File",
        "description": "Streams a source file after authorizing its sourcefile- resource ID with the caller's Bearer token. This route does not accept or mint a document session token and is separate from the OnlyOffice flow.",
        "operationId": "streamSourceFile",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SourceFileRequest"
              },
              "example": {
                "resource_id": "sourcefile-org-id/input/protocol.pdf"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Source file bytes"
          },
          "400": {
            "description": "The resource ID is not a sourcefile resource"
          },
          "401": {
            "description": "Missing, invalid, or unauthorized Bearer token"
          }
        }
      }
    },
    "/generate-onlyoffice-config": {
      "post": {
        "tags": ["Files"],
        "summary": "Create OnlyOffice Configuration",
        "description": "Authorize a resource and return a server-generated OnlyOffice configuration. Use readonly mode for previews.",
        "operationId": "generateOnlyOfficeConfig",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GenerateOnlyOfficeConfigRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OnlyOffice configuration created",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GenerateOnlyOfficeConfigResponse"
                }
              }
            }
          },
          "400": {
            "description": "Invalid mode or request body"
          },
          "401": {
            "description": "Missing, invalid, or unauthorized Bearer token"
          },
          "500": {
            "description": "Document session service is unavailable"
          }
        }
      }
    },
    "/open-document": {
      "get": {
        "tags": ["Files"],
        "summary": "Stream a Document Session",
        "description": "Streams document bytes for a viewer using a short-lived session token sent in the Authorization header. A session token in the query string is rejected for ordinary downloads; the query form is reserved for the OnlyOffice server-to-server flow and requires a separate signed OnlyOffice JWT. This route does not accept S3 URLs or raw object keys.",
        "operationId": "openDocument",
        "security": [
          {
            "documentSessionAuth": []
          }
        ],
        "parameters": [
          {
            "name": "session_token",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "OnlyOffice compatibility parameter. Do not use this query parameter for ordinary downloads; send the session token as Authorization: Bearer instead."
          }
        ],
        "responses": {
          "200": {
            "description": "Document stream",
            "content": {
              "application/octet-stream": {
                "schema": {
                  "type": "string",
                  "format": "binary"
                }
              }
            }
          },
          "401": {
            "description": "Missing, invalid, expired, or revoked session token"
          },
          "500": {
            "description": "Unable to retrieve document"
          }
        }
      }
    },
    "/api/v1/files/{container}": {
      "get": {
        "tags": ["Files"],
        "summary": "List Files",
        "description": "List all files in a specific container for the authenticated user's organization. Returns file names and resource IDs. Resolve each resource ID through the authenticated document-session endpoint.",
        "operationId": "listFiles",
        "parameters": [
          {
            "name": "container",
            "in": "path",
            "required": true,
            "description": "Container/folder name (e.g., 'templates', 'documents', 'input')",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ListFilesResponse"
                },
                "example": {
                  "files": [
                    {
                      "name": "protocol.pdf",
                      "resource_id": "sourcefile-org-id/documents/protocol.pdf"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Authentication failure"
          },
          "500": {
            "description": "S3 operation failed"
          }
        }
      }
    },
    "/api/v1/files/upload": {
      "post": {
        "tags": ["Files"],
        "summary": "Upload File",
        "description": "Upload a file to S3. Validates file type by extension/MIME. Auto-converts DOCX to PDF except in the templates container.",
        "operationId": "uploadFile",
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "properties": {
                  "file_name": {
                    "type": "string",
                    "description": "Name to give the file"
                  },
                  "file_content": {
                    "type": "string",
                    "format": "binary",
                    "description": "File content"
                  },
                  "container": {
                    "type": "string",
                    "description": "Container/folder name for upload"
                  }
                },
                "required": ["file_name", "file_content", "container"]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "File uploaded successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "File validation failure"
          },
          "401": {
            "description": "Authentication failure"
          },
          "500": {
            "description": "S3 upload failed"
          }
        }
      }
    },
    "/api/v1/documents/": {
      "get": {
        "tags": ["Documents"],
        "summary": "List Documents",
        "description": "List all documents for the authenticated user. Internal/Owner role users see all documents in their organization. Other roles see only their own documents.",
        "operationId": "listDocuments",
        "responses": {
          "200": {
            "description": "Documents retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "documents": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "document_id": { "type": "string" },
                          "document_name": { "type": "string" },
                          "document_type": { "type": "string" },
                          "status": { "type": "string" },
                          "created_at": { "type": "string", "format": "date-time" },
                          "updated_at": { "type": "string", "format": "date-time" }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Authentication failed"
          },
          "403": {
            "description": "User has no organization"
          }
        }
      }
    },
    "/api/v1/documents/generate": {
      "post": {
        "tags": ["Documents"],
        "summary": "Generate Document",
        "description": "Extract content from source documents, ingest, and orchestrate document generation using a template. Request is immediately queued as a background task and returns 202 Accepted. Poll `/api/v1/documents/status/{document_id}` for progress.\n\n**Field aliases** (both forms accepted):\n- `connector_data_id` = `document_set_key`\n- `template_id` = `generic_mrt_id`\n- `workspace_name` = `document_set_name`",
        "operationId": "generateDocument",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GenerateDocumentRequest"
              },
              "example": {
                "document_type": "CSR",
                "file_paths": ["org-id/documents/protocol.pdf", "org-id/documents/study-report.pdf"],
                "connector_data_id": "project-2024-001",
                "workspace_name": "Q1 CSR Documents",
                "template_id": "template-uuid-123",
                "output_name": "CSR_Final"
              }
            }
          }
        },
        "responses": {
          "202": {
            "description": "Request accepted for processing",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TaskAcceptedResponse"
                },
                "example": {
                  "message": "Request to generate document has been accepted and is being processed in the background.",
                  "task_id": "document-uuid-456"
                }
              }
            }
          },
          "400": {
            "description": "Missing required parameters or document set not found"
          },
          "401": {
            "description": "Authentication failure"
          },
          "500": {
            "description": "Database operation failed"
          }
        }
      }
    },
    "/api/v1/documents/status/{document_id}": {
      "get": {
        "tags": ["Documents"],
        "summary": "Get Document Status",
        "description": "Poll the status of a document being generated. Returns current processing state from the database.",
        "operationId": "getDocumentStatus",
        "parameters": [
          {
            "name": "document_id",
            "in": "path",
            "required": true,
            "description": "UUID of document",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Status retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TaskStatusResponse"
                },
                "example": {
                  "task_id": "document-uuid-456",
                  "status": "Generating",
                  "progress": null,
                  "error": null
                }
              }
            }
          },
          "404": {
            "description": "Document not found"
          },
          "500": {
            "description": "Database error"
          }
        }
      }
    },
    "/api/v1/documents/{document_id}": {
      "get": {
        "tags": ["Documents"],
        "summary": "Get Document",
        "description": "Get a single document by ID with sections, sources, and metadata. Only returns documents belonging to the authenticated user's organization.",
        "operationId": "getDocument",
        "parameters": [
          {
            "name": "document_id",
            "in": "path",
            "required": true,
            "description": "UUID of document",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Document retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GetDocumentFromIdResponse"
                }
              }
            }
          },
          "401": {
            "description": "Authentication failed or missing token"
          },
          "403": {
            "description": "User has no organization"
          },
          "404": {
            "description": "Document not found or not accessible"
          },
          "500": {
            "description": "Database error"
          }
        }
      }
    },
    "/api/v1/document-sets/": {
      "get": {
        "tags": ["Document Sets"],
        "summary": "List Document Sets",
        "description": "List all document sets for the authenticated user. Internal/Owner role users see all document sets in their organization.",
        "operationId": "listDocumentSets",
        "responses": {
          "200": {
            "description": "Document sets retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GetAllDocumentSetsResponse"
                },
                "example": {
                  "document_sets": [
                    {
                      "document_set_id": "ds-uuid-001",
                      "document_set_name": "Q1 CSR Documents",
                      "organization_id": "org-uuid-123",
                      "details": null,
                      "documents": ["doc-uuid-456"],
                      "version": 1
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Authentication failed"
          }
        }
      },
      "post": {
        "tags": ["Document Sets"],
        "summary": "Create Document Set",
        "description": "Create a new document set associated to the authenticated user's organization. Creator is automatically added to the users array.\n\n**Field alias**: `workspace_name` is the primary field name; `document_set_name` is also accepted.",
        "operationId": "createDocumentSet",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateDocumentSetRequest"
              },
              "example": {
                "workspace_name": "Q1 CSR Documents"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Document set created successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentSetResponse"
                },
                "example": {
                  "document_set_id": "ds-uuid-001",
                  "document_set_name": "Q1 CSR Documents",
                  "organization_id": "org-uuid-123",
                  "details": null,
                  "documents": [],
                  "version": 1
                }
              }
            }
          },
          "400": {
            "description": "Authentication failed or missing token"
          },
          "500": {
            "description": "Database error during creation"
          }
        }
      }
    },
    "/api/v1/document-sets/{document_set_id}": {
      "get": {
        "tags": ["Document Sets"],
        "summary": "Get Document Set",
        "description": "Get a single document set by ID including all associated documents and users. Organization-scoped.",
        "operationId": "getDocumentSet",
        "parameters": [
          {
            "name": "document_set_id",
            "in": "path",
            "required": true,
            "description": "UUID of document set",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Document set retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GetOneDocumentSetResponse"
                }
              }
            }
          },
          "400": {
            "description": "Authentication failed or document set not found"
          },
          "403": {
            "description": "Not authorized to access this document set"
          }
        }
      }
    },
    "/api/v1/templates/": {
      "get": {
        "tags": ["Templates"],
        "summary": "List Templates",
        "description": "List all templates accessible to the authenticated user. Filtered by organization and user membership, sorted by creation date (newest first).",
        "operationId": "listTemplates",
        "responses": {
          "200": {
            "description": "Templates listed successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ListAllTemplatesResponse"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": ["Templates"],
        "summary": "Create Template",
        "description": "Create a new template with nested sections and rules. Validates inputs and persists to database.",
        "operationId": "createTemplate",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateTemplateRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Template created successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CreateTemplateResponse"
                }
              }
            }
          },
          "400": {
            "description": "Validation errors"
          },
          "401": {
            "description": "Authentication failures"
          },
          "500": {
            "description": "Database operation failures"
          }
        }
      }
    },
    "/api/v1/templates/{template_id}": {
      "get": {
        "tags": ["Templates"],
        "summary": "Get Template",
        "description": "Retrieve a single template by ID with full details including sections and users.",
        "operationId": "getTemplate",
        "parameters": [
          {
            "name": "template_id",
            "in": "path",
            "required": true,
            "description": "UUID of template",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Template retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GetOneTemplateResponse"
                }
              }
            }
          },
          "400": {
            "description": "Authentication failure"
          },
          "404": {
            "description": "Template not found"
          }
        }
      }
    },
    "/api/v1/templates/{template_id}/sections": {
      "post": {
        "tags": ["Templates"],
        "summary": "Add Template Section",
        "description": "Add a new section to an existing template.",
        "operationId": "addTemplateSection",
        "parameters": [
          {
            "name": "template_id",
            "in": "path",
            "required": true,
            "description": "UUID of template",
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AddTemplateSectionRequest"
              },
              "example": {
                "section_name": "3. Safety Summary",
                "level": 1,
                "order_index": 2
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Section added successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AddTemplateSectionResponse"
                }
              }
            }
          },
          "400": {
            "description": "Authentication errors"
          },
          "403": {
            "description": "Unauthorized access"
          },
          "404": {
            "description": "Template not found"
          },
          "500": {
            "description": "Database operation failures"
          }
        }
      }
    },
    "/api/v1/templates/{template_id}/sections/{section_id}": {
      "delete": {
        "tags": ["Templates"],
        "summary": "Delete Template Section",
        "description": "Delete a section from a template with optional cascading of child sections. Database CASCADE handles deletion of associated rules.",
        "operationId": "deleteTemplateSection",
        "parameters": [
          {
            "name": "template_id",
            "in": "path",
            "required": true,
            "description": "UUID of template",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "section_id",
            "in": "path",
            "required": true,
            "description": "UUID of section to delete",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "cascade_children",
            "in": "query",
            "required": false,
            "description": "Whether to delete child sections with higher levels (default: true)",
            "schema": {
              "type": "boolean",
              "default": true
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Section deleted successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeleteTemplateSectionResponse"
                }
              }
            }
          },
          "400": {
            "description": "Invalid parameters"
          },
          "403": {
            "description": "Not authorized"
          },
          "404": {
            "description": "Template or section not found"
          }
        }
      }
    },
    "/api/v1/templates/{template_id}/sections/{section_id}/rename": {
      "put": {
        "tags": ["Templates"],
        "summary": "Rename Template Section",
        "description": "Rename a section in an existing template. Provide the full new name (e.g., '2.1 Efficacy Results').",
        "operationId": "renameTemplateSection",
        "parameters": [
          {
            "name": "template_id",
            "in": "path",
            "required": true,
            "description": "UUID of template",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "section_id",
            "in": "path",
            "required": true,
            "description": "UUID of section to rename",
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RenameSectionRequest"
              },
              "example": {
                "section_name": "2.1 Efficacy Results"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Section renamed successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RenameSectionResponse"
                }
              }
            }
          },
          "400": {
            "description": "Authentication errors"
          },
          "403": {
            "description": "Unauthorized access"
          },
          "404": {
            "description": "Template or section not found"
          },
          "500": {
            "description": "Database operation failures"
          }
        }
      }
    },
    "/api/v1/templates/{template_id}/sections/reorder": {
      "put": {
        "tags": ["Templates"],
        "summary": "Reorder Template Sections",
        "description": "Reorder and renumber template sections. After applying the new positions, all section names are automatically renumbered to reflect the hierarchy (e.g., '1.', '1.1', '2.').",
        "operationId": "reorderTemplateSections",
        "parameters": [
          {
            "name": "template_id",
            "in": "path",
            "required": true,
            "description": "UUID of template",
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ReorderSectionsRequest"
              },
              "example": {
                "sections": [
                  { "section_id": "sec-uuid-001", "order_index": 0, "level": 1 },
                  { "section_id": "sec-uuid-003", "order_index": 1, "level": 1 },
                  { "section_id": "sec-uuid-002", "order_index": 2, "level": 1 }
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Sections reordered successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReorderSectionsResponse"
                }
              }
            }
          },
          "400": {
            "description": "Authentication errors"
          },
          "403": {
            "description": "Unauthorized access"
          },
          "404": {
            "description": "Template not found"
          },
          "500": {
            "description": "Database operation failures"
          }
        }
      }
    },
    "/api/v1/templates/{template_id}/rules/{rule_id}/styles": {
      "put": {
        "tags": ["Templates"],
        "summary": "Update Rule Styles",
        "description": "Update style names, fill color, and/or text color for a template section rule. Styles are returned automatically with the Get Template endpoint.",
        "operationId": "updateRuleStyles",
        "parameters": [
          {
            "name": "template_id",
            "in": "path",
            "required": true,
            "description": "UUID of template (for authorization)",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "rule_id",
            "in": "path",
            "required": true,
            "description": "UUID of rule to update",
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateRuleStylesRequest"
              },
              "example": {
                "style_names": ["Heading 2", "Normal"],
                "fill": "#FFFF00",
                "color": null
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Rule styles updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UpdateRuleStylesResponse"
                }
              }
            }
          },
          "400": {
            "description": "Authentication errors"
          },
          "403": {
            "description": "Unauthorized access"
          },
          "404": {
            "description": "Template or rule not found"
          },
          "500": {
            "description": "Database operation failures"
          }
        }
      }
    },
    "/api/v1/mrt-outlines/{outline_id}": {
      "get": {
        "tags": ["Outlines"],
        "summary": "Get Outline",
        "description": "Get a single outline by ID. Returns the complete outline including metadata and all sections ordered by index. Organization-scoped.",
        "operationId": "getOutline",
        "parameters": [
          {
            "name": "outline_id",
            "in": "path",
            "required": true,
            "description": "UUID of outline",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Outline retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GetOneMRTOutlineResponse"
                }
              }
            }
          },
          "400": {
            "description": "Authentication failed or outline not found"
          },
          "403": {
            "description": "User not authorized"
          }
        }
      },
      "put": {
        "tags": ["Outlines"],
        "summary": "Update Outline",
        "description": "Full replacement (PUT) of an outline. All existing sections are deleted and replaced with the provided structure.",
        "operationId": "updateOutline",
        "parameters": [
          {
            "name": "outline_id",
            "in": "path",
            "required": true,
            "description": "UUID of outline",
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateOutlineRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Outline updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GetOneMRTOutlineResponse"
                }
              }
            }
          },
          "400": {
            "description": "Invalid outline structure"
          },
          "401": {
            "description": "Authentication failed"
          },
          "403": {
            "description": "User not authorized"
          },
          "404": {
            "description": "Outline not found"
          },
          "500": {
            "description": "Database error"
          }
        }
      }
    },
    "/api/v1/document-mrt/{mrt_id}": {
      "put": {
        "tags": ["Document Details"],
        "summary": "Update Document Details",
        "description": "Full replacement (PUT) of document details including metadata, sections, and rules. All existing sections and rules are deleted and replaced.",
        "operationId": "updateDocumentDetails",
        "parameters": [
          {
            "name": "mrt_id",
            "in": "path",
            "required": true,
            "description": "UUID of the document details record",
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateDocumentDetailsRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Document details updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GetOneMRTOutlineResponse"
                }
              }
            }
          },
          "400": {
            "description": "Invalid structure"
          },
          "401": {
            "description": "Authentication failed"
          },
          "403": {
            "description": "User not authorized"
          },
          "404": {
            "description": "Document details record or parent document not found"
          },
          "422": {
            "description": "Request validation error"
          },
          "500": {
            "description": "Database error"
          }
        }
      }
    },
    "/api/v1/document-mrt/by-document/{document_id}": {
      "get": {
        "tags": ["Document Details"],
        "summary": "Get Document Details by Document ID",
        "description": "Get document details by parent document ID. Retrieves complete details with all sections and rules for the specified document.",
        "operationId": "getDocumentDetailsByDocumentId",
        "parameters": [
          {
            "name": "document_id",
            "in": "path",
            "required": true,
            "description": "UUID of parent document",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Document details retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GetOneMRTOutlineResponse"
                }
              }
            }
          },
          "401": {
            "description": "Authentication failed"
          },
          "403": {
            "description": "User not authorized"
          },
          "404": {
            "description": "Document not found or no details found"
          },
          "500": {
            "description": "Database error"
          }
        }
      }
    },
    "/get-sections-for-document": {
      "post": {
        "tags": ["Documents"],
        "summary": "Get Sections for Document",
        "description": "Retrieve a flat list of all section identifiers and their associated metadata within a given document. Used to enumerate the full section structure, enabling the Sources panel selection dropdown to be pre-populated with all available sections upon document load.",
        "operationId": "getSectionsForDocument",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GetSectionsForDocumentRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Sections retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GetSectionsForDocumentResponse"
                },
                "example": {
                  "sections": [
                    {
                      "section_id": "1.1 Title of Study:",
                      "section_title": "1.1 Title of Study:",
                      "section_order": 0
                    },
                    {
                      "section_id": "1.2 Study Objectives:",
                      "section_title": "1.2 Study Objectives:",
                      "section_order": 1
                    },
                    {
                      "section_id": "1.3 Study Design:",
                      "section_title": "1.3 Study Design:",
                      "section_order": 2
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Authentication failed or invalid Bearer token"
          },
          "404": {
            "description": "Document MRT not found for the given document ID"
          }
        }
      }
    }
  }
}
