openapi: 3.1.0
info:
  title: learnalgorithms.dev API
  version: 1.1.0
  description: >
    Privacy-preserving REST API for learnalgorithms.dev. Implemented using only the
    Python standard library with SQLite persistence. Stores no personal data or IP addresses.
servers:
  - url: https://api.learnalgorithms.dev
    description: Production server

components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      description: Random 256-bit admin token (`ADMIN_TOKEN`), compared in constant time.
    GitHubSignature:
      type: apiKey
      in: header
      name: X-Hub-Signature-256
      description: HMAC-SHA256 signature (`sha256=<hex>`) computed with `GITHUB_WEBHOOK_SECRET`.
  schemas:
    ErrorResponse:
      type: object
      required: [error]
      properties:
        error:
          type: string
    FeedbackRequest:
      type: object
      required: [page, helpful, elapsed]
      properties:
        page:
          type: string
          pattern: '^/concepts(/[a-z0-9][a-z0-9-]{0,80}){1,3}/?$'
          example: /concepts/sorting/quicksort
        helpful:
          type: boolean
        comment:
          type: [string, 'null']
          maxLength: 500
        elapsed:
          type: integer
          minimum: 0
          description: Time spent on page in milliseconds (submissions < 3000 ms are silently discarded).
        website:
          type: string
          description: Honeypot field; must remain empty.
        client:
          type: [string, 'null']
          format: uuid
          description: Optional random UUID generated in browser localStorage to distinguish students behind a shared campus IP.
    TelemetryEvent:
      type: object
      required: [sessionId, eventType, page]
      properties:
        sessionId:
          type: string
          format: uuid
        eventType:
          type: string
          enum:
            - page_view
            - page_leave
            - lesson_complete
            - lesson_uncomplete
            - cheat_sheet_filter
            - cheat_sheet_compare
            - visualizer_interact
            - search
            - details_open
            - resource_click
            - web_vitals
        page:
          type: string
          example: /concepts/sorting/quicksort
        durationMs:
          type: [integer, 'null']
          minimum: 0
          maximum: 3600000
        scrollPct:
          type: [integer, 'null']
          minimum: 0
          maximum: 100
        meta:
          type: [object, 'null']
          additionalProperties:
            type: [string, number, boolean, 'null']
          description: Optional sanitized key-value metadata (max 512 bytes serialized).

paths:
  /health:
    get:
      summary: Liveness check
      responses:
        '200':
          description: API is healthy
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    example: ok

  /feedback:
    post:
      summary: Submit anonymous lesson feedback
      description: Requires `Origin: https://learnalgorithms.dev`. Limited to one vote per page, client, and day.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/FeedbackRequest'
      responses:
        '201':
          description: Feedback stored
        '200':
          description: Already voted for this page today
        '202':
          description: Silently discarded (bot check)
        '400':
          description: Validation error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Origin not allowed
        '429':
          description: Rate limit exceeded

  /feedback/summary:
    get:
      summary: Aggregated helpfulness votes for one page
      parameters:
        - name: page
          in: query
          required: true
          schema:
            type: string
            example: /concepts/sorting/quicksort
      responses:
        '200':
          description: Vote counts
          content:
            application/json:
              schema:
                type: object
                properties:
                  page:
                    type: string
                  helpful:
                    type: integer
                  notHelpful:
                    type: integer
        '400':
          description: Invalid page parameter
        '429':
          description: Rate limit exceeded

  /popular:
    get:
      summary: Most read lessons of the last 7 days
      description: Fetched from Matomo over HTTPS and cached for 15 minutes; degrades gracefully to an empty list on error.
      responses:
        '200':
          description: Top pages
          content:
            application/json:
              schema:
                type: object
                properties:
                  pages:
                    type: array
                    items:
                      type: object
                      properties:
                        page:
                          type: string
                        visits:
                          type: integer

  /events:
    post:
      summary: Record anonymous student/usage telemetry events
      description: Accepts a single event object or a batch (`events`, max 20 items, max 4 KB body). Requires `Origin: https://learnalgorithms.dev`.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - $ref: '#/components/schemas/TelemetryEvent'
                - type: object
                  required: [events]
                  properties:
                    events:
                      type: array
                      minItems: 1
                      maxItems: 20
                      items:
                        $ref: '#/components/schemas/TelemetryEvent'
      responses:
        '201':
          description: Events stored
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    example: stored
                  count:
                    type: integer
        '400':
          description: Validation error
        '403':
          description: Origin not allowed
        '429':
          description: Rate limit exceeded

  /webhooks/github:
    post:
      summary: Receive GitHub issue webhooks
      security:
        - GitHubSignature: []
      parameters:
        - name: X-GitHub-Event
          in: header
          required: true
          schema:
            type: string
        - name: X-GitHub-Delivery
          in: header
          required: false
          schema:
            type: string
      responses:
        '200':
          description: Ping acknowledged
        '202':
          description: Non-issue event ignored
        '204':
          description: Issue event stored
        '400':
          description: Invalid payload
        '401':
          description: Invalid HMAC signature

  /admin/feedback:
    get:
      summary: Latest feedback votes and comments
      security:
        - BearerAuth: []
      responses:
        '200':
          description: Latest feedback entries
        '401':
          description: Unauthorized

  /admin/issues:
    get:
      summary: Latest GitHub issue webhook events
      security:
        - BearerAuth: []
      responses:
        '200':
          description: Latest recorded GitHub issue events
        '401':
          description: Unauthorized

  /admin/stats:
    get:
      summary: Aggregated learning analytics summary
      security:
        - BearerAuth: []
      parameters:
        - name: days
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 365
            default: 30
      responses:
        '200':
          description: Aggregated totals, top pages (views, avg duration, avg scroll), lesson completions, and daily series
        '400':
          description: Invalid days parameter
        '401':
          description: Unauthorized

  /admin/events:
    get:
      summary: Export anonymized telemetry events (JSON or CSV)
      security:
        - BearerAuth: []
      parameters:
        - name: days
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 365
            default: 30
        - name: limit
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 5000
            default: 500
        - name: format
          in: query
          required: false
          schema:
            type: string
            enum: [json, csv]
            default: json
      responses:
        '200':
          description: Anonymized events in JSON or downloadable CSV (`learnalgorithms-events.csv`)
          content:
            application/json:
              schema:
                type: object
                properties:
                  events:
                    type: array
                    items:
                      $ref: '#/components/schemas/TelemetryEvent'
            text/csv:
              schema:
                type: string
        '400':
          description: Invalid query parameter
        '401':
          description: Unauthorized

  /survey:
    post:
      summary: Submit anonymous course satisfaction survey (1-5 scale)
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [clarity, usefulness, tools, overall]
              properties:
                clarity: { type: integer, minimum: 1, maximum: 5 }
                usefulness: { type: integer, minimum: 1, maximum: 5 }
                tools: { type: integer, minimum: 1, maximum: 5 }
                overall: { type: integer, minimum: 1, maximum: 5 }
                comment: { type: string, maxLength: 500, nullable: true }
                elapsed: { type: number }
                website: { type: string }
                client: { type: string, format: uuid }
      responses:
        '201': { description: Survey response saved or updated }
        '202': { description: Silently discarded by bot protection }
        '400': { description: Invalid ratings or comment }
        '403': { description: Origin not allowed }

  /questions:
    post:
      summary: Ask an anonymous private question
      description: No account, contact data or IP is stored. Returns a one-time ticket; only its SHA-256 hash is kept.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [question]
              properties:
                question: { type: string, minLength: 1, maxLength: 2000 }
                page: { type: string, nullable: true, example: /concepts/sorting/quicksort }
                elapsed: { type: number }
                website: { type: string }
      responses:
        '201': { description: 'Saved; returns {"status":"saved","ticket":"K7Q4-MXP2-D9RT"}' }
        '202': { description: Silently discarded by bot protection }
        '400': { description: Invalid question or page }
        '403': { description: Origin not allowed }

  /questions/status:
    post:
      summary: Status and answers of up to 20 tickets
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [tickets]
              properties:
                tickets:
                  type: array
                  minItems: 1
                  maxItems: 20
                  items: { type: string, pattern: '^[2-9A-HJKMNP-Z]{4}-[2-9A-HJKMNP-Z]{4}-[2-9A-HJKMNP-Z]{4}$' }
      responses:
        '200': { description: Known tickets with status (pending | answered) and answer }
        '400': { description: Invalid tickets }

  /admin/docs/{name}:
    get:
      summary: Private Markdown document (current content and versions)
      security:
        - BearerAuth: []
      parameters:
        - { name: name, in: path, required: true, schema: { type: string, pattern: '^[a-z0-9][a-z0-9-]{0,39}$' } }
      responses:
        '200': { description: 'Content, update time and the list of versions' }
        '401': { description: Unauthorized }
    post:
      summary: Save a new version (identical content is not duplicated; the last 100 versions are kept)
      security:
        - BearerAuth: []
      parameters:
        - { name: name, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [content]
              properties:
                content: { type: string, maxLength: 1000000 }
      responses:
        '200': { description: Unchanged }
        '201': { description: Saved }
        '400': { description: Invalid content }
        '401': { description: Unauthorized }

  /admin/docs/{name}/versions/{id}:
    get:
      summary: One saved version of a private document
      security:
        - BearerAuth: []
      parameters:
        - { name: name, in: path, required: true, schema: { type: string } }
        - { name: id, in: path, required: true, schema: { type: integer } }
      responses:
        '200': { description: Content of that version }
        '401': { description: Unauthorized }
        '404': { description: Not found }

  /admin/tasks:
    get:
      summary: Teacher's private to-do list
      security:
        - BearerAuth: []
      responses:
        '200': { description: 'Tasks: id, title, description, due (optional deadline), priority (1 high, 2 medium, 3 low), done, created (set automatically), doneAt. Tasks done more than 10 days ago are deleted.' }
        '401': { description: Unauthorized }
    post:
      summary: Create one task, or several with {"tasks": [...]} (up to 200)
      security:
        - BearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                title: { type: string, maxLength: 200 }
                description: { type: string, nullable: true }
                due: { type: string, format: date, nullable: true }
                priority: { type: integer, enum: [1, 2, 3], default: 2 }
                done: { type: boolean, default: false }
                tasks: { type: array, maxItems: 200, items: { type: object } }
      responses:
        '201': { description: 'Created; returns the new ids' }
        '400': { description: Invalid task }
        '401': { description: Unauthorized }

  /admin/tasks/{id}:
    post:
      summary: Update some fields of a task
      security:
        - BearerAuth: []
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer } }
      responses:
        '200': { description: Updated }
        '400': { description: Invalid task }
        '401': { description: Unauthorized }
        '404': { description: Not found }
    delete:
      summary: Delete a task
      security:
        - BearerAuth: []
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer } }
      responses:
        '200': { description: Deleted }
        '401': { description: Unauthorized }
        '404': { description: Not found }

  /admin/questions:
    get:
      summary: Anonymous questions inbox
      security:
        - BearerAuth: []
      parameters:
        - name: status
          in: query
          required: false
          schema: { type: string, enum: [all, pending, answered], default: all }
      responses:
        '200': { description: Questions, newest first }
        '401': { description: Unauthorized }

  /admin/questions/{id}/answer:
    post:
      summary: Answer a question privately (only the holder of the ticket sees it)
      security:
        - BearerAuth: []
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [answer]
              properties:
                answer: { type: string, minLength: 1, maxLength: 2000 }
      responses:
        '200': { description: Answered }
        '400': { description: Invalid answer }
        '401': { description: Unauthorized }
        '404': { description: Not found }

  /admin/questions/{id}:
    delete:
      summary: Delete a question
      security:
        - BearerAuth: []
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer } }
      responses:
        '200': { description: Deleted }
        '401': { description: Unauthorized }
        '404': { description: Not found }

  /admin/survey:
    get:
      summary: Aggregated course satisfaction survey results
      security:
        - BearerAuth: []
      parameters:
        - name: days
          in: query
          required: false
          schema: { type: integer, minimum: 0, maximum: 3650, default: 30 }
      responses:
        '200': { description: Averages (1-5), distribution, and recent entries }
        '401': { description: Unauthorized }

  /admin/report:
    get:
      summary: Consolidated ETL teaching report (JSON or Markdown)
      security:
        - BearerAuth: []
      parameters:
        - name: days
          in: query
          required: false
          schema: { type: integer, minimum: 0, maximum: 3650, default: 30 }
        - name: format
          in: query
          required: false
          schema: { type: string, enum: [json, md], default: json }
      responses:
        '200': { description: Structured ETL JSON + Markdown report including NLP, Core Web Vitals, Green Software (SWDM), feedback, and survey }
        '401': { description: Unauthorized }

  /admin/report/interpret:
    post:
      summary: AI-assisted pedagogical interpretation of the anonymized ETL report
      security:
        - BearerAuth: []
      parameters:
        - name: days
          in: query
          required: false
          schema: { type: integer, minimum: 0, maximum: 3650, default: 30 }
        - name: lang
          in: query
          required: false
          schema: { type: string, enum: [en, es], default: en }
        - name: detail
          in: query
          required: false
          schema: { type: string, enum: [brief, detailed], default: brief }
      responses:
        '200': { description: Structured Markdown pedagogical analysis (also persisted in SQLite history) }
        '401': { description: Unauthorized }
        '429': { description: LLM rate limit exceeded }
        '502': { description: Upstream LLM error }
        '503': { description: LLM_API_KEY not configured }

  /admin/report/history:
    get:
      summary: List previously saved AI pedagogical reports from SQLite
      security:
        - BearerAuth: []
      parameters:
        - name: limit
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 100, default: 25 }
      responses:
        '200': { description: Ordered list of saved AI report interpretations }
        '401': { description: Unauthorized }

  /admin/report/history/{id}:
    delete:
      summary: Delete a saved AI pedagogical report from SQLite
      security:
        - BearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: integer }
      responses:
        '200': { description: Deleted }
        '401': { description: Unauthorized }
        '404': { description: Not found }

  /admin/metrics:
    get:
      summary: Prometheus text exposition metrics (0.0.4)
      security:
        - BearerAuth: []
      responses:
        '200':
          description: Live process uptime, HTTP request count, SQLite size, telemetry/feedback totals, and rolling 30-day Web Vitals p95
          content:
            text/plain:
              schema: { type: string }
        '401': { description: Unauthorized }
