openapi: 3.0.3
info:
  title: KARA Project API
  description: |
    # Korean Archives Recovery from America API
    
    KARA Project의 공식 REST API. 미국 NARA 한국 관련 기록 검색·조회·분석 서비스를 제공합니다.
    
    ## 주요 기능
    - 📄 **문서 검색**: 다국어 전문 검색, 15차원 메타데이터 필터링
    - 👤 **인물 DB**: 한미 관계 주요 인물 조회
    - 🗺️ **GIS 검색**: 지리 기반 위치 검색
    - 📅 **타임라인**: 시간순 사건 조회
    - 📊 **통계**: RG별/시대별 분포 분석
    - 🤖 **AI 분석**: 문서 자동 요약, 번역, 개체 인식
    
    ## 인증
    공개 API는 인증 없이 사용 가능합니다. 고급 기능(다운로드, 대량 조회 등)은 API 키가 필요합니다.
    
    ## Rate Limit
    - 익명: 100 req/hour
    - 등록 사용자: 1,000 req/hour
    - 연구자: 10,000 req/hour
    - 학술 기관: 무제한
    
    ## Soli Deo Gloria
    
  version: 1.0.0
  contact:
    name: KARA Project Development Team
    email: api@kara.archives.go.kr
    url: https://kara.archives.go.kr/developers
  license:
    name: CC BY 4.0
    url: https://creativecommons.org/licenses/by/4.0/

servers:
  - url: https://api.kara.archives.go.kr/v1
    description: Production
  - url: https://staging-api.kara.archives.go.kr/v1
    description: Staging
  - url: http://localhost:8000/v1
    description: Local Development

tags:
  - name: documents
    description: 📄 문서 검색 및 조회
  - name: persons
    description: 👤 인물 데이터베이스
  - name: locations
    description: 🗺️ 장소 (PostGIS 지원)
  - name: events
    description: 📅 역사적 사건
  - name: search
    description: 🔍 통합 검색
  - name: ai
    description: 🤖 AI 분석 서비스
  - name: stats
    description: 📊 통계 및 분석
  - name: admin
    description: 🔐 관리자 (인증 필요)

paths:
  # =========================================================
  # DOCUMENTS
  # =========================================================
  /documents:
    get:
      tags: [documents]
      summary: 문서 목록 조회
      description: |
        조건에 맞는 문서 목록을 페이지네이션으로 반환합니다.
        15차원 메타데이터 필터 모두 지원됩니다.
      operationId: listDocuments
      parameters:
        - $ref: '#/components/parameters/PageParam'
        - $ref: '#/components/parameters/LimitParam'
        - name: rg
          in: query
          description: Record Group 필터 (예 'RG 59', 'RG 554')
          schema:
            type: string
            example: "RG 59"
        - name: classification
          in: query
          description: 분류 등급
          schema:
            type: string
            enum: [UNCLASSIFIED, CONFIDENTIAL, SECRET, TOP_SECRET, TOP_SECRET_UMBRA, EYES_ONLY]
        - name: period
          in: query
          description: 역사적 시기
          schema:
            type: string
            enum: [pre_colonial, japanese_colonial, liberation, first_republic, korean_war, second_republic, park_era, chun_era, roh_era, modern]
        - name: date_from
          in: query
          description: 시작일 (ISO 8601)
          schema:
            type: string
            format: date
            example: "1950-06-25"
        - name: date_to
          in: query
          description: 종료일
          schema:
            type: string
            format: date
            example: "1953-07-27"
        - name: sort
          in: query
          schema:
            type: string
            enum: [date_asc, date_desc, importance, relevance, citation_count]
            default: date_desc
      responses:
        '200':
          description: 문서 목록 반환 성공
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DocumentListResponse'
              examples:
                korean_war:
                  summary: 한국전쟁 문서 예시
                  value:
                    total: 312
                    page: 1
                    limit: 20
                    items:
                      - document_code: "RG59-4501-F2-D3"
                        title_en: "Memorandum of Telephone Conversation"
                        title_ko: "트루먼-애치슨 통화록 1950.6.24"
                        creation_date: "1950-06-24"
                        rg: "RG 59"
                        classification: "TOP_SECRET"
                        importance_score: 5
        '400':
          $ref: '#/components/responses/BadRequest'

  /documents/{document_code}:
    get:
      tags: [documents]
      summary: 단일 문서 상세 조회
      description: 15차원 메타데이터 완전 정보 반환
      operationId: getDocument
      parameters:
        - name: document_code
          in: path
          required: true
          schema:
            type: string
            example: "RG59-4501-F2-D3"
      responses:
        '200':
          description: 문서 상세 정보
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Document'
        '404':
          $ref: '#/components/responses/NotFound'

  /documents/{document_code}/analysis:
    get:
      tags: [documents]
      summary: 15차원 분석 결과 조회
      operationId: getDocumentAnalysis
      parameters:
        - name: document_code
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: 차원별 분석 결과
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DocumentAnalysis'

  /documents/{document_code}/translations:
    get:
      tags: [documents]
      summary: 문서 번역 조회
      operationId: getDocumentTranslations
      parameters:
        - name: document_code
          in: path
          required: true
          schema:
            type: string
        - name: target_lang
          in: query
          schema:
            type: string
            enum: [ko, en, ja, zh]
            default: ko
      responses:
        '200':
          description: 번역 텍스트
          content:
            application/json:
              schema:
                type: object
                properties:
                  source_language: { type: string }
                  target_language: { type: string }
                  translated_text: { type: string }
                  translation_method: { type: string }
                  quality_score: { type: number }

  /documents/{document_code}/citations:
    get:
      tags: [documents]
      summary: 학술 인용 목록
      operationId: getDocumentCitations
      parameters:
        - name: document_code
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: 인용 목록
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Citation'

  # =========================================================
  # SEARCH
  # =========================================================
  /search:
    get:
      tags: [search]
      summary: 통합 전문 검색
      description: |
        한국어와 영어 동시 검색을 지원합니다. 동의어 매핑이 자동 적용되어
        "한국전쟁"으로 검색해도 "Korean War" 결과가 함께 반환됩니다.
      operationId: search
      parameters:
        - name: q
          in: query
          required: true
          schema:
            type: string
            example: "광주"
          description: 검색어 (한·영 자동 변환)
        - $ref: '#/components/parameters/PageParam'
        - $ref: '#/components/parameters/LimitParam'
        - name: types
          in: query
          description: 검색 대상 (콤마 구분)
          schema:
            type: string
            example: "documents,persons,events"
            default: "documents"
      responses:
        '200':
          description: 검색 결과
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchResponse'

  /search/suggest:
    get:
      tags: [search]
      summary: 자동완성 제안
      operationId: searchSuggest
      parameters:
        - name: q
          in: query
          required: true
          schema:
            type: string
      responses:
        '200':
          description: 제안 목록
          content:
            application/json:
              schema:
                type: object
                properties:
                  suggestions:
                    type: array
                    items:
                      type: object
                      properties:
                        text: { type: string }
                        type: { type: string }
                        match_count: { type: integer }

  # =========================================================
  # PERSONS
  # =========================================================
  /persons:
    get:
      tags: [persons]
      summary: 인물 목록 조회
      operationId: listPersons
      parameters:
        - $ref: '#/components/parameters/PageParam'
        - $ref: '#/components/parameters/LimitParam'
        - name: country
          in: query
          schema:
            type: string
            enum: [USA, ROK, DPRK, JAPAN, CHINA, USSR, UK, OTHER]
        - name: q
          in: query
          description: 이름 검색
          schema:
            type: string
            example: "박정희"
      responses:
        '200':
          description: 인물 목록
          content:
            application/json:
              schema:
                type: object
                properties:
                  total: { type: integer }
                  items:
                    type: array
                    items:
                      $ref: '#/components/schemas/Person'

  /persons/{id}:
    get:
      tags: [persons]
      summary: 인물 상세 정보
      operationId: getPerson
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: 인물 상세
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Person'

  /persons/{id}/documents:
    get:
      tags: [persons]
      summary: 인물 관련 문서 조회
      operationId: getPersonDocuments
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
        - name: relation
          in: query
          schema:
            type: string
            enum: [sender, receiver, mentioned, all]
            default: all
      responses:
        '200':
          description: 관련 문서 목록
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DocumentListResponse'

  /persons/{id}/network:
    get:
      tags: [persons]
      summary: 인물 관계 네트워크 (지식 그래프)
      operationId: getPersonNetwork
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
        - name: depth
          in: query
          description: 그래프 깊이 (1-3)
          schema:
            type: integer
            minimum: 1
            maximum: 3
            default: 1
      responses:
        '200':
          description: 관계 그래프
          content:
            application/json:
              schema:
                type: object
                properties:
                  nodes:
                    type: array
                    items:
                      $ref: '#/components/schemas/GraphNode'
                  edges:
                    type: array
                    items:
                      $ref: '#/components/schemas/GraphEdge'

  # =========================================================
  # LOCATIONS (GIS)
  # =========================================================
  /locations:
    get:
      tags: [locations]
      summary: 장소 목록 조회
      operationId: listLocations
      parameters:
        - name: country
          in: query
          schema:
            type: string
        - name: type
          in: query
          schema:
            type: string
            enum: [city, province, country, building, mountain, island]
      responses:
        '200':
          description: 장소 목록
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Location'

  /locations/nearby:
    get:
      tags: [locations]
      summary: GIS 근접 검색 (PostGIS)
      description: 특정 좌표 주변의 문서/장소를 검색합니다.
      operationId: findNearby
      parameters:
        - name: lat
          in: query
          required: true
          schema:
            type: number
            example: 37.5665
          description: 위도
        - name: lng
          in: query
          required: true
          schema:
            type: number
            example: 126.978
          description: 경도
        - name: radius
          in: query
          schema:
            type: integer
            default: 50000
          description: 반경 (미터)
      responses:
        '200':
          description: 근접 문서·장소
          content:
            application/json:
              schema:
                type: object
                properties:
                  center: { type: object }
                  radius_m: { type: integer }
                  documents:
                    type: array
                    items:
                      type: object
                      properties:
                        document_code: { type: string }
                        title_ko: { type: string }
                        distance_m: { type: integer }

  # =========================================================
  # EVENTS
  # =========================================================
  /events:
    get:
      tags: [events]
      summary: 역사적 사건 목록
      operationId: listEvents
      parameters:
        - name: date_from
          in: query
          schema:
            type: string
            format: date
        - name: date_to
          in: query
          schema:
            type: string
            format: date
        - name: type
          in: query
          schema:
            type: string
            enum: [war, treaty, demonstration, election, coup, assassination, uprising, liberation, civil_conflict, military_operation, diplomatic, revolution]
      responses:
        '200':
          description: 사건 목록
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Event'

  /events/timeline:
    get:
      tags: [events]
      summary: 타임라인 데이터 (시각화용)
      operationId: getTimeline
      parameters:
        - name: year_from
          in: query
          schema:
            type: integer
            default: 1880
        - name: year_to
          in: query
          schema:
            type: integer
            default: 1990
      responses:
        '200':
          description: 타임라인 데이터
          content:
            application/json:
              schema:
                type: object
                properties:
                  decades:
                    type: array
                    items:
                      type: object
                      properties:
                        year: { type: integer }
                        event_count: { type: integer }
                        is_major: { type: boolean }
                  events:
                    type: array
                    items:
                      $ref: '#/components/schemas/Event'

  # =========================================================
  # AI SERVICES
  # =========================================================
  /ai/summarize:
    post:
      tags: [ai]
      summary: AI 문서 요약 생성
      operationId: aiSummarize
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [document_code]
              properties:
                document_code: { type: string }
                target_lang: 
                  type: string
                  enum: [ko, en]
                  default: ko
                length:
                  type: string
                  enum: [short, medium, long]
                  default: medium
      responses:
        '200':
          description: 요약 결과
          content:
            application/json:
              schema:
                type: object
                properties:
                  summary: { type: string }
                  language: { type: string }
                  word_count: { type: integer }
                  ai_model: { type: string }
                  confidence: { type: number }

  /ai/translate:
    post:
      tags: [ai]
      summary: AI 번역
      operationId: aiTranslate
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [text, target_lang]
              properties:
                text: { type: string }
                source_lang: 
                  type: string
                  enum: [auto, en, ko, ja, zh]
                  default: auto
                target_lang:
                  type: string
                  enum: [en, ko, ja, zh]
      responses:
        '200':
          description: 번역 결과

  /ai/extract-entities:
    post:
      tags: [ai]
      summary: 개체 추출 (NER)
      operationId: aiExtractEntities
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                text: { type: string }
                document_code: { type: string }
                entity_types:
                  type: array
                  items:
                    type: string
                    enum: [PERSON, LOCATION, ORGANIZATION, DATE, EVENT, MONEY]
      responses:
        '200':
          description: 추출된 개체
          content:
            application/json:
              schema:
                type: object
                properties:
                  entities:
                    type: array
                    items:
                      type: object
                      properties:
                        text: { type: string }
                        type: { type: string }
                        confidence: { type: number }
                        position: { type: object }

  # =========================================================
  # STATISTICS
  # =========================================================
  /stats/overview:
    get:
      tags: [stats]
      summary: 전체 통계 개요
      operationId: getStatsOverview
      responses:
        '200':
          description: 통계 데이터
          content:
            application/json:
              schema:
                type: object
                properties:
                  total_record_groups: { type: integer }
                  total_documents: { type: integer }
                  total_pages_digitized: { type: integer }
                  total_persons: { type: integer }
                  total_events: { type: integer }
                  documents_by_rg:
                    type: array
                    items:
                      type: object
                      properties:
                        rg_number: { type: string }
                        count: { type: integer }
                  documents_by_period:
                    type: object
                  documents_by_classification:
                    type: object

  /stats/progress:
    get:
      tags: [stats]
      summary: 사업 진행률
      operationId: getProgress
      responses:
        '200':
          description: 진행률 데이터
          content:
            application/json:
              schema:
                type: object
                properties:
                  overall_progress_pct: { type: number }
                  rgs_completed: { type: integer }
                  rgs_in_progress: { type: integer }
                  by_tier:
                    type: object
                    properties:
                      S: { type: object }
                      A: { type: object }
                      B: { type: object }
                      C: { type: object }

# =============================================================================
# COMPONENTS
# =============================================================================
components:
  parameters:
    PageParam:
      name: page
      in: query
      description: 페이지 번호 (1부터 시작)
      schema:
        type: integer
        minimum: 1
        default: 1
    LimitParam:
      name: limit
      in: query
      description: 페이지당 항목 수
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 20

  schemas:
    Document:
      type: object
      properties:
        id: { type: string, format: uuid }
        document_code: { type: string, example: "RG59-4501-F2-D3" }
        title_en: { type: string }
        title_ko: { type: string }
        rg: { type: string }
        box: { type: string }
        folder: { type: string }
        creation_date: { type: string, format: date }
        creation_time: { type: string }
        classification:
          type: string
          enum: [UNCLASSIFIED, CONFIDENTIAL, SECRET, TOP_SECRET, TOP_SECRET_UMBRA]
        declassification_status:
          type: string
          enum: [CLASSIFIED, PARTIALLY_DECLASSIFIED, DECLASSIFIED, PUBLICLY_RELEASED]
        sender_name: { type: string }
        receiver_name: { type: string }
        primary_location_name: { type: string }
        primary_location_gps:
          type: object
          properties:
            lat: { type: number }
            lng: { type: number }
        importance_score: { type: integer, minimum: 1, maximum: 5 }
        historical_period: { type: string }
        word_count: { type: integer }
        summary_ko: { type: string }
        summary_en: { type: string }
        tags:
          type: array
          items: { type: string }
        key_persons:
          type: array
          items: { type: string }
        key_events:
          type: array
          items: { type: string }
        key_locations:
          type: array
          items: { type: string }

    DocumentAnalysis:
      type: object
      properties:
        document_code: { type: string }
        dimensions:
          type: object
          properties:
            physical: { type: object }
            temporal: { type: object }
            organizational: { type: object }
            content: { type: object }
            linguistic: { type: object }
            material: { type: object }
            geographical: { type: object }

    DocumentListResponse:
      type: object
      properties:
        total: { type: integer }
        page: { type: integer }
        limit: { type: integer }
        items:
          type: array
          items:
            $ref: '#/components/schemas/Document'

    Person:
      type: object
      properties:
        id: { type: integer }
        name_en: { type: string }
        name_ko: { type: string }
        country:
          type: string
          enum: [USA, ROK, DPRK, JAPAN, CHINA, USSR, UK, OTHER]
        birth_date: { type: string, format: date }
        death_date: { type: string, format: date }
        primary_role: { type: string }
        biography_en: { type: string }
        biography_ko: { type: string }
        documents_authored: { type: integer }
        documents_received: { type: integer }
        documents_mentioned: { type: integer }

    Location:
      type: object
      properties:
        id: { type: integer }
        name_en: { type: string }
        name_ko: { type: string }
        location_type: { type: string }
        country: { type: string }
        coordinates:
          type: object
          properties:
            lat: { type: number }
            lng: { type: number }
        document_count: { type: integer }
        event_count: { type: integer }
        significance_text: { type: string }

    Event:
      type: object
      properties:
        id: { type: integer }
        name_en: { type: string }
        name_ko: { type: string }
        name_short: { type: string }
        event_type: { type: string }
        date_start: { type: string, format: date }
        date_end: { type: string, format: date }
        primary_location: { type: object }
        summary_ko: { type: string }
        casualties_dead: { type: integer }
        document_count: { type: integer }

    Citation:
      type: object
      properties:
        id: { type: integer }
        citing_work_title: { type: string }
        citing_work_authors:
          type: array
          items: { type: string }
        citing_work_year: { type: integer }
        citing_work_journal: { type: string }
        citation_format: { type: string }
        page_range: { type: string }

    GraphNode:
      type: object
      properties:
        id: { type: integer }
        type: { type: string }
        label: { type: string }
        country: { type: string }

    GraphEdge:
      type: object
      properties:
        source: { type: integer }
        target: { type: integer }
        relationship_type: { type: string }
        strength: { type: number }
        description: { type: string }

    SearchResponse:
      type: object
      properties:
        query: { type: string }
        expanded_terms:
          type: array
          items: { type: string }
        total_results: { type: integer }
        results:
          type: object
          properties:
            documents:
              type: array
              items: { $ref: '#/components/schemas/Document' }
            persons:
              type: array
              items: { $ref: '#/components/schemas/Person' }
            events:
              type: array
              items: { $ref: '#/components/schemas/Event' }

    Error:
      type: object
      properties:
        error:
          type: object
          properties:
            code: { type: string }
            message: { type: string }
            details: { type: object }

  responses:
    BadRequest:
      description: 잘못된 요청
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: "INVALID_PARAMETER"
              message: "잘못된 파라미터입니다."

    NotFound:
      description: 리소스를 찾을 수 없음
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: "NOT_FOUND"
              message: "요청하신 리소스를 찾을 수 없습니다."

  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: |
        API 키 발급: https://kara.archives.go.kr/developers/apply
        
        - 익명: 키 없이 사용 가능 (100 req/hour)
        - 등록 사용자: 무료 등록 후 키 발급 (1,000 req/hour)
        - 연구자: 학술 인증 후 발급 (10,000 req/hour)
        - 학술 기관: 기관 협약 후 무제한
