{
  "openapi": "3.1.0",
  "info": {
    "title": "CinematicAds API",
    "version": "1.0.0",
    "description": "AI-Powered Video Advertising Automation API. Generate cinematic video ads, manage brand assets, track creative performance, and optimize campaigns — all through a unified REST API.",
    "contact": {
      "name": "CinematicAds Support",
      "url": "https://cinematicads.studio",
      "email": "contact@cinematicads.studio"
    },
    "license": {
      "name": "Proprietary",
      "url": "https://cinematicads.studio/terms"
    }
  },
  "servers": [
    {
      "url": "https://cinematicads.studio/api",
      "description": "Production"
    }
  ],
  "tags": [
    { "name": "Auth", "description": "Authentication & session management" },
    { "name": "Workflow", "description": "AI video generation workflows" },
    { "name": "User", "description": "User profile, credits & settings" },
    { "name": "Brand", "description": "Brand profile & knowledge base" },
    { "name": "API Key", "description": "Self-service API key management (Agency/Enterprise)" },
    { "name": "Projects", "description": "Generated video projects" },
    { "name": "Billing", "description": "Credits, purchases & invoices" },
    { "name": "Chat", "description": "AI operator chat assistant" },
    { "name": "Prompt Builder", "description": "Structured prompt construction (zero-token)" },
    { "name": "Performance", "description": "Creative performance tracking & analytics" },
    { "name": "Config", "description": "Public configuration endpoints" },
    { "name": "Health", "description": "System health & capabilities" },
    { "name": "Moderation", "description": "Content moderation & DSA compliance" },
    { "name": "Notifications", "description": "Push notification management" },
    { "name": "Admin", "description": "Admin-only endpoints (requires admin role)" }
  ],
  "components": {
    "securitySchemes": {
      "cookieAuth": {
        "type": "apiKey",
        "in": "cookie",
        "name": "session",
        "description": "JWT session cookie (set by POST /auth/login)"
      },
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT",
        "description": "API key (ca_ prefix) or JWT token via Authorization header"
      }
    },
    "schemas": {
      "ApiResponse": {
        "type": "object",
        "required": ["success"],
        "properties": {
          "success": { "type": "boolean" },
          "data": { "description": "Response payload (when success=true)" },
          "error": { "type": "string", "description": "Error message (when success=false)" }
        }
      },
      "AuthCredentials": {
        "type": "object",
        "required": ["email", "password"],
        "properties": {
          "email": { "type": "string", "format": "email" },
          "password": { "type": "string", "minLength": 8, "maxLength": 128 }
        }
      },
      "AuthResponse": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "email": { "type": "string", "format": "email" },
          "role": { "type": "string", "enum": ["user", "admin"] }
        }
      },
      "UserSession": {
        "type": "object",
        "properties": {
          "userId": { "type": "string" },
          "email": { "type": "string", "format": "email" },
          "role": { "type": "string", "enum": ["user", "admin"] },
          "expiresAt": { "type": "integer", "description": "Unix timestamp" },
          "trialEndsAt": { "type": "string", "format": "date-time", "nullable": true }
        }
      },
      "UserProfile": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "email": { "type": "string", "format": "email" },
          "role": { "type": "string", "enum": ["user", "admin"] },
          "credits_balance": { "type": "integer" },
          "current_plan_id": { "$ref": "#/components/schemas/PlanId" },
          "provider_preference": { "$ref": "#/components/schemas/ProviderPreference" },
          "created_at": { "type": "string", "format": "date-time" },
          "last_login": { "type": "string", "format": "date-time", "nullable": true },
          "status": { "type": "string", "enum": ["active", "suspended"] },
          "trial_ends_at": { "type": "string", "format": "date-time", "nullable": true },
          "has_api_key": { "type": "boolean" }
        }
      },
      "PlanId": {
        "type": "string",
        "enum": ["free", "trial", "subscription_starter", "subscription_pro", "subscription_agency", "subscription_enterprise", "pack_10", "pack_25", "pack_50", "pack_100"]
      },
      "ProviderPreference": {
        "type": "string",
        "enum": ["auto", "kling", "veo"],
        "default": "auto"
      },
      "QualityTier": {
        "type": "string",
        "enum": ["standard", "premium"],
        "default": "standard",
        "description": "Standard = cost-optimized, Premium = quality-maximized"
      },
      "WorkflowType": {
        "type": "string",
        "enum": ["cinematic", "avatar", "factory", "clone", "influencer", "brand", "staticad", "painpoint", "ad-optimizer"],
        "description": "Client-facing workflow types"
      },
      "WorkflowRequest": {
        "type": "object",
        "required": ["type"],
        "properties": {
          "type": { "$ref": "#/components/schemas/WorkflowType" },
          "url": { "type": "string", "format": "uri", "description": "Target URL (required for clone, factory)" },
          "concept": { "type": "string", "maxLength": 2000, "description": "Creative concept / prompt" },
          "brand": { "type": "string", "description": "Brand ID for brand context injection" },
          "models": {
            "type": "object",
            "properties": {
              "image": { "type": "string" },
              "video": { "type": "string" },
              "voice": { "type": "string" }
            }
          },
          "formats": {
            "type": "array",
            "items": { "type": "string", "enum": ["16:9", "9:16", "1:1", "4:5"] },
            "description": "Target aspect ratios (factory workflow)"
          },
          "quality": { "$ref": "#/components/schemas/QualityTier" },
          "async": { "type": "boolean", "default": true, "description": "Async mode returns jobId for SSE tracking" },
          "hitl": { "type": "boolean", "default": false, "description": "Enable Human-in-the-Loop review" },
          "framework": {
            "type": "string",
            "enum": ["pas", "aida", "sb7", "cialdini", "uvp", "bant"],
            "description": "Marketing framework for script generation"
          },
          "seasonal": {
            "type": "string",
            "enum": ["ramadan", "eid"],
            "description": "Seasonal template override"
          },
          "adPreset": { "type": "string", "description": "Cinematic style preset" },
          "imagesOnly": { "type": "boolean", "default": false, "description": "Skip video generation (factory)" },
          "publish": { "type": "boolean", "default": false, "description": "Auto-publish to social platforms" }
        }
      },
      "WorkflowResponse": {
        "type": "object",
        "properties": {
          "jobId": { "type": "string", "description": "Job ID for SSE progress tracking" },
          "status": { "type": "string", "enum": ["queued", "processing", "completed", "failed"] },
          "creditsUsed": { "type": "integer" },
          "result": {
            "type": "object",
            "properties": {
              "finalVideo": { "type": "string", "description": "URL of generated video" },
              "thumbnail": { "type": "string" },
              "assets": {
                "type": "array",
                "items": { "$ref": "#/components/schemas/OutputAsset" }
              }
            }
          }
        }
      },
      "OutputAsset": {
        "type": "object",
        "properties": {
          "url": { "type": "string", "format": "uri" },
          "type": { "type": "string", "enum": ["video", "image", "audio"] },
          "format": { "type": "string", "description": "Aspect ratio (16:9, 9:16, etc.)" },
          "duration": { "type": "number", "description": "Duration in seconds" },
          "platform": { "type": "string", "description": "Target platform" }
        }
      },
      "BrandProfile": {
        "type": "object",
        "properties": {
          "brandName": { "type": "string", "maxLength": 100 },
          "brandColors": { "type": "string", "maxLength": 200, "description": "Comma-separated hex colors" },
          "brandVoice": { "type": "string", "maxLength": 500 },
          "targetAudience": { "type": "string", "maxLength": 500 },
          "brandValues": { "type": "string", "maxLength": 500 },
          "industry": { "type": "string", "maxLength": 100 },
          "productDescription": { "type": "string", "maxLength": 1000 },
          "competitorUrls": { "type": "string", "maxLength": 500 },
          "websiteUrl": { "type": "string", "format": "uri" },
          "socialLinks": { "type": "string", "maxLength": 500 },
          "logoUrl": { "type": "string", "format": "uri" },
          "styleGuide": { "type": "string", "maxLength": 2000 },
          "preferredLanguage": { "type": "string", "maxLength": 10 }
        }
      },
      "KnowledgeBaseItem": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "type": { "type": "string", "enum": ["file", "url"] },
          "name": { "type": "string" },
          "status": { "type": "string", "enum": ["ready", "extracting", "error"] },
          "mimeType": { "type": "string" },
          "size": { "type": "integer" },
          "extractedText": { "type": "string" },
          "created_at": { "type": "string", "format": "date-time" }
        }
      },
      "Project": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "user_id": { "type": "string" },
          "type": { "type": "string" },
          "status": { "type": "string", "enum": ["pending", "processing", "completed", "failed"] },
          "input_data": { "type": "string" },
          "output_data": { "type": "string" },
          "credits_used": { "type": "integer" },
          "created_at": { "type": "string", "format": "date-time" }
        }
      },
      "Capability": {
        "type": "object",
        "properties": {
          "name": { "type": "string" },
          "category": { "type": "string" },
          "tier": { "type": "string" },
          "status": { "type": "string", "enum": ["active", "deprecated"] },
          "isNew": { "type": "boolean" },
          "features": { "type": "array", "items": { "type": "string" } }
        }
      },
      "PromptSchema": {
        "type": "object",
        "properties": {
          "version": { "type": "string" },
          "builders": { "type": "array", "items": { "type": "string" } },
          "schemas": { "type": "object" },
          "cinematographyStyles": { "type": "object" },
          "lexicon": { "type": "object" }
        }
      },
      "PromptBuildRequest": {
        "type": "object",
        "required": ["builder"],
        "properties": {
          "builder": { "type": "string", "enum": ["imagen4", "veo31", "kling26"] },
          "params": {
            "type": "object",
            "properties": {
              "subject": { "type": "string" },
              "context": { "type": "string" },
              "style": { "type": "string" },
              "quality": { "type": "string" },
              "lighting": { "type": "string" },
              "camera": { "type": "string" },
              "negative": { "type": "array", "items": { "type": "string" } }
            }
          }
        }
      },
      "CreditPack": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "credits": { "type": "integer" },
          "price": { "type": "number" },
          "currency": { "type": "string" }
        }
      },
      "Error429": {
        "type": "object",
        "properties": {
          "success": { "const": false },
          "error": { "type": "string", "example": "Too many requests. Please try again later." }
        }
      }
    },
    "responses": {
      "Unauthorized": {
        "description": "Authentication required or invalid token",
        "content": {
          "application/json": {
            "schema": {
              "type": "object",
              "properties": {
                "success": { "const": false },
                "error": { "type": "string", "example": "Authentication required" }
              }
            }
          }
        }
      },
      "RateLimited": {
        "description": "Rate limit exceeded",
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/Error429" }
          }
        }
      },
      "InternalError": {
        "description": "Internal server error",
        "content": {
          "application/json": {
            "schema": {
              "type": "object",
              "properties": {
                "success": { "const": false },
                "error": { "type": "string", "example": "Internal server error" }
              }
            }
          }
        }
      }
    }
  },
  "security": [
    { "cookieAuth": [] },
    { "bearerAuth": [] }
  ],
  "paths": {
    "/auth/signup": {
      "post": {
        "tags": ["Auth"],
        "summary": "Create a new account",
        "description": "Register a new user account. Choose a plan to start producing video ads.",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/AuthCredentials" }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Account created, session cookie set",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    { "$ref": "#/components/schemas/ApiResponse" },
                    { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/AuthResponse" } } }
                  ]
                }
              }
            }
          },
          "400": { "description": "Validation error" },
          "409": { "description": "Email already registered" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/auth/login": {
      "post": {
        "tags": ["Auth"],
        "summary": "Log in",
        "description": "Authenticate and receive a session cookie (httpOnly, secure).",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/AuthCredentials" }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Login successful, session cookie set",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    { "$ref": "#/components/schemas/ApiResponse" },
                    { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/AuthResponse" } } }
                  ]
                }
              }
            }
          },
          "401": { "description": "Invalid credentials" },
          "403": { "description": "Account suspended" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/auth/session": {
      "get": {
        "tags": ["Auth"],
        "summary": "Get current session",
        "responses": {
          "200": {
            "description": "Current session details",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    { "$ref": "#/components/schemas/ApiResponse" },
                    { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/UserSession" } } }
                  ]
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/auth/logout": {
      "post": {
        "tags": ["Auth"],
        "summary": "Log out",
        "description": "Revoke session token and clear cookie.",
        "responses": {
          "200": { "description": "Logged out" }
        }
      }
    },
    "/workflow": {
      "post": {
        "tags": ["Workflow"],
        "summary": "Launch AI video generation",
        "description": "Submit a workflow job. Credits are deducted before execution. In async mode (default), returns a jobId for SSE progress tracking via /workflow/stream.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/WorkflowRequest" }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Workflow result (sync) or job queued (async)",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    { "$ref": "#/components/schemas/ApiResponse" },
                    { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/WorkflowResponse" } } }
                  ]
                }
              }
            }
          },
          "400": { "description": "Invalid workflow type or parameters" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "402": { "description": "Insufficient credits or trial expired" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/workflow/stream": {
      "get": {
        "tags": ["Workflow"],
        "summary": "Stream workflow progress (SSE)",
        "description": "Server-Sent Events endpoint for real-time progress. User isolation enforced (can only stream own jobs).",
        "parameters": [
          {
            "name": "jobId",
            "in": "query",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": {
            "description": "SSE stream with progress events",
            "content": {
              "text/event-stream": {
                "schema": {
                  "type": "string",
                  "description": "SSE events: data: {type, step, progress, status, result}"
                }
              }
            }
          },
          "404": { "description": "Job not found" }
        }
      },
      "post": {
        "tags": ["Workflow"],
        "summary": "Update workflow progress",
        "description": "Update job state (used by worker processes).",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["jobId"],
                "properties": {
                  "jobId": { "type": "string" },
                  "step": { "type": "string" },
                  "progress": { "type": "integer", "minimum": 0, "maximum": 100 },
                  "status": { "type": "string", "enum": ["processing", "completed", "failed"] },
                  "result": { "type": "object" }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Progress updated" }
        }
      }
    },
    "/workflow/hitl": {
      "get": {
        "tags": ["Workflow"],
        "summary": "Check HITL review status",
        "description": "Check if a workflow is waiting for Human-in-the-Loop approval. Auto-refunds credits if pending >24h.",
        "parameters": [
          { "name": "jobId", "in": "query", "required": true, "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "HITL state with preview data" }
        }
      },
      "post": {
        "tags": ["Workflow"],
        "summary": "Submit HITL review decision",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["jobId", "action"],
                "properties": {
                  "jobId": { "type": "string" },
                  "action": { "type": "string", "enum": ["approve", "reject"] },
                  "feedback": { "type": "string" }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Review submitted" }
        }
      }
    },
    "/workflow/review": {
      "get": {
        "tags": ["Workflow"],
        "summary": "Get review history",
        "responses": {
          "200": { "description": "Review history for user's workflows" }
        }
      },
      "post": {
        "tags": ["Workflow"],
        "summary": "Submit quality rating",
        "description": "Rate generated content (thumbs up/down + optional feedback).",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["projectId", "rating"],
                "properties": {
                  "projectId": { "type": "string" },
                  "rating": { "type": "string", "enum": ["up", "down"] },
                  "feedback": { "type": "string", "maxLength": 500 }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Rating saved" }
        }
      }
    },
    "/user/credits": {
      "get": {
        "tags": ["Billing"],
        "summary": "Get credit balance",
        "responses": {
          "200": {
            "description": "Current credit balance",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    { "$ref": "#/components/schemas/ApiResponse" },
                    { "type": "object", "properties": { "data": { "type": "object", "properties": { "balance": { "type": "integer" } } } } }
                  ]
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/user/credits/purchase": {
      "get": {
        "tags": ["Billing"],
        "summary": "Get available credit packs",
        "responses": {
          "200": { "description": "Available credit packs with pricing" }
        }
      },
      "post": {
        "tags": ["Billing"],
        "summary": "Purchase a credit pack",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["packId"],
                "properties": {
                  "packId": { "type": "string", "enum": ["pack_10", "pack_25", "pack_50", "pack_100"] }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Payment session URL returned" },
          "402": { "description": "Payment failed" }
        }
      }
    },
    "/user/profile": {
      "get": {
        "tags": ["User"],
        "summary": "Get user profile",
        "responses": {
          "200": {
            "description": "User profile details",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    { "$ref": "#/components/schemas/ApiResponse" },
                    { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/UserProfile" } } }
                  ]
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/user/stats": {
      "get": {
        "tags": ["User"],
        "summary": "Get usage statistics",
        "responses": {
          "200": { "description": "User usage statistics" }
        }
      }
    },
    "/user/analytics": {
      "get": {
        "tags": ["User"],
        "summary": "Get analytics data",
        "responses": {
          "200": { "description": "User analytics" }
        }
      }
    },
    "/user/change-password": {
      "post": {
        "tags": ["User"],
        "summary": "Change password",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["currentPassword", "newPassword"],
                "properties": {
                  "currentPassword": { "type": "string" },
                  "newPassword": { "type": "string", "minLength": 8 }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Password changed" }
        }
      }
    },
    "/user/provider-preference": {
      "get": {
        "tags": ["User"],
        "summary": "Get video provider preference",
        "responses": {
          "200": { "description": "Current provider preference (auto/kling/veo)" }
        }
      },
      "post": {
        "tags": ["User"],
        "summary": "Set video provider preference",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["preference"],
                "properties": {
                  "preference": { "$ref": "#/components/schemas/ProviderPreference" }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Preference saved" }
        }
      }
    },
    "/user/brand": {
      "get": {
        "tags": ["Brand"],
        "summary": "Get brand profile",
        "responses": {
          "200": {
            "description": "Brand profile",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    { "$ref": "#/components/schemas/ApiResponse" },
                    { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/BrandProfile" } } }
                  ]
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": ["Brand"],
        "summary": "Create or update brand profile",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/BrandProfile" }
            }
          }
        },
        "responses": {
          "200": { "description": "Brand profile saved" }
        }
      }
    },
    "/user/brand/knowledge": {
      "get": {
        "tags": ["Brand"],
        "summary": "List knowledge base items",
        "description": "Get all uploaded files and registered URLs in the brand knowledge base.",
        "responses": {
          "200": {
            "description": "Knowledge base items",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    { "$ref": "#/components/schemas/ApiResponse" },
                    { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/KnowledgeBaseItem" } } } }
                  ]
                }
              }
            }
          }
        }
      }
    },
    "/user/brand/knowledge/files": {
      "post": {
        "tags": ["Brand"],
        "summary": "Upload knowledge base file",
        "description": "Upload PDF, DOCX, XLSX, CSV, or TXT files. Max 9 files, 50MB each. Content is extracted for AI context.",
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "properties": {
                  "file": { "type": "string", "format": "binary" }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "File uploaded and extraction started" },
          "400": { "description": "Invalid file type or quota exceeded" }
        }
      }
    },
    "/user/brand/knowledge/urls": {
      "post": {
        "tags": ["Brand"],
        "summary": "Add knowledge base URL",
        "description": "Scrape and index a URL for AI context. Max 10 URLs.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["url"],
                "properties": {
                  "url": { "type": "string", "format": "uri" }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "URL added and scraping started" }
        }
      }
    },
    "/user/brand/knowledge/{id}": {
      "get": {
        "tags": ["Brand"],
        "summary": "Get knowledge base item detail",
        "parameters": [
          { "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "Knowledge base item with extracted text" }
        }
      },
      "delete": {
        "tags": ["Brand"],
        "summary": "Delete knowledge base item",
        "parameters": [
          { "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "Item deleted" }
        }
      }
    },
    "/user/brand/schedule": {
      "get": {
        "tags": ["Brand"],
        "summary": "Get brand publishing schedule",
        "responses": {
          "200": { "description": "Schedule configuration" }
        }
      },
      "post": {
        "tags": ["Brand"],
        "summary": "Update brand publishing schedule",
        "responses": {
          "200": { "description": "Schedule updated" }
        }
      }
    },
    "/user/projects": {
      "get": {
        "tags": ["Projects"],
        "summary": "List generated projects",
        "description": "Returns all user's generated video projects sorted by creation date (newest first).",
        "responses": {
          "200": {
            "description": "Project list",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    { "$ref": "#/components/schemas/ApiResponse" },
                    { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/Project" } } } }
                  ]
                }
              }
            }
          }
        }
      }
    },
    "/user/projects/export": {
      "get": {
        "tags": ["Projects"],
        "summary": "Export projects as CSV",
        "responses": {
          "200": {
            "description": "CSV file download",
            "content": { "text/csv": {} }
          }
        }
      }
    },
    "/user/api-key": {
      "get": {
        "tags": ["API Key"],
        "summary": "Check API key status",
        "description": "Check if the user has an API key and is eligible (Agency/Enterprise plans only).",
        "responses": {
          "200": {
            "description": "API key status",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    { "$ref": "#/components/schemas/ApiResponse" },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "hasApiKey": { "type": "boolean" },
                            "eligible": { "type": "boolean" },
                            "currentPlan": { "$ref": "#/components/schemas/PlanId" },
                            "eligiblePlans": { "type": "array", "items": { "type": "string" } }
                          }
                        }
                      }
                    }
                  ]
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": ["API Key"],
        "summary": "Generate API key",
        "description": "Generate a new API key (ca_ prefix). Shown once — save it immediately. Requires Agency or Enterprise plan.",
        "responses": {
          "200": {
            "description": "API key generated (show-once)",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    { "$ref": "#/components/schemas/ApiResponse" },
                    { "type": "object", "properties": { "data": { "type": "object", "properties": { "apiKey": { "type": "string", "example": "ca_a1b2c3d4-e5f6-7890-abcd-ef1234567890" } } } } }
                  ]
                }
              }
            }
          },
          "403": { "description": "Plan does not support API keys" }
        }
      },
      "delete": {
        "tags": ["API Key"],
        "summary": "Revoke API key",
        "responses": {
          "200": { "description": "API key revoked" }
        }
      }
    },
    "/invoice/generate": {
      "get": {
        "tags": ["Billing"],
        "summary": "List invoices",
        "responses": {
          "200": { "description": "Invoice list" }
        }
      },
      "post": {
        "tags": ["Billing"],
        "summary": "Generate invoice PDF",
        "responses": {
          "200": {
            "description": "PDF invoice",
            "content": { "application/pdf": {} }
          }
        }
      }
    },
    "/prompt-builder": {
      "get": {
        "tags": ["Prompt Builder"],
        "summary": "Get prompt schemas",
        "description": "Returns available builders, camera specs, cinematography styles, and lexicon. Zero-token (no LLM calls).",
        "security": [],
        "responses": {
          "200": {
            "description": "Prompt builder schemas and metadata",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    { "$ref": "#/components/schemas/ApiResponse" },
                    { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/PromptSchema" } } }
                  ]
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": ["Prompt Builder"],
        "summary": "Build structured prompt",
        "description": "Convert natural language prompt to optimized structured prompt. Zero-token computation.",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/PromptBuildRequest" }
            }
          }
        },
        "responses": {
          "200": { "description": "Built prompt with quality score" }
        }
      }
    },
    "/chat/query": {
      "post": {
        "tags": ["Chat"],
        "summary": "Query AI operator assistant",
        "description": "Chat with the AI operator. Supports Generative UI with tool calling (planCampaign, getPerformance, etc.). SSE streaming.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["message"],
                "properties": {
                  "message": { "type": "string", "maxLength": 2000 },
                  "threadId": { "type": "string" }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "SSE stream with AI response",
            "content": { "text/event-stream": {} }
          }
        }
      }
    },
    "/chat/history": {
      "get": {
        "tags": ["Chat"],
        "summary": "Get chat history",
        "responses": {
          "200": { "description": "Chat conversation history" }
        }
      }
    },
    "/loop": {
      "get": {
        "tags": ["Performance"],
        "summary": "Get Loop Engine recommendation",
        "description": "Get the autonomous optimization recommendation for a brand's creatives (SEED, DOUBLE_DOWN, ITERATE, KILL, CHALLENGER).",
        "parameters": [
          { "name": "brandId", "in": "query", "required": true, "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "Loop engine recommendation with reasoning" }
        }
      },
      "post": {
        "tags": ["Performance"],
        "summary": "Execute Loop Engine action",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["brandId", "action"],
                "properties": {
                  "brandId": { "type": "string" },
                  "action": { "type": "string", "enum": ["SEED", "DOUBLE_DOWN", "ITERATE", "KILL", "CHALLENGER"] }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Action executed" }
        }
      }
    },
    "/workflow/performance": {
      "get": {
        "tags": ["Performance"],
        "summary": "Get creative performance data",
        "responses": {
          "200": { "description": "Performance metrics with creative decay detection" }
        }
      },
      "post": {
        "tags": ["Performance"],
        "summary": "Ingest performance metrics",
        "description": "Submit ad performance data (impressions, clicks, conversions, spend).",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["creativeId"],
                "properties": {
                  "creativeId": { "type": "string" },
                  "impressions": { "type": "integer" },
                  "clicks": { "type": "integer" },
                  "conversions": { "type": "integer" },
                  "spend": { "type": "number" },
                  "revenue": { "type": "number" }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Metrics ingested with computed CTR/ROAS" }
        }
      },
      "patch": {
        "tags": ["Performance"],
        "summary": "Update performance metrics",
        "responses": {
          "200": { "description": "Metrics updated" }
        }
      }
    },
    "/performance": {
      "post": {
        "tags": ["Performance"],
        "summary": "Submit performance data",
        "responses": {
          "200": { "description": "Performance data recorded" }
        }
      }
    },
    "/batch/status": {
      "get": {
        "tags": ["Workflow"],
        "summary": "Get batch job status",
        "description": "Check progress of batch workflow jobs.",
        "parameters": [
          { "name": "batchId", "in": "query", "required": true, "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "Batch status with per-job progress" }
        }
      }
    },
    "/models/status": {
      "get": {
        "tags": ["Health"],
        "summary": "Get AI capabilities",
        "description": "Returns platform capabilities. Provider names are NEVER exposed (abstracted to category/tier).",
        "security": [],
        "responses": {
          "200": {
            "description": "Platform capabilities and recent upgrades",
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    { "$ref": "#/components/schemas/ApiResponse" },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "capabilities": { "type": "array", "items": { "$ref": "#/components/schemas/Capability" } },
                            "recentUpgrades": { "type": "array", "items": { "type": "object" } },
                            "stats": {
                              "type": "object",
                              "properties": {
                                "totalCapabilities": { "type": "integer" },
                                "recentlyUpdated": { "type": "integer" },
                                "categories": { "type": "integer" }
                              }
                            }
                          }
                        }
                      }
                    }
                  ]
                }
              }
            }
          }
        }
      }
    },
    "/health": {
      "get": {
        "tags": ["Health"],
        "summary": "Health check",
        "description": "Returns system status. Response is stripped to {status, timestamp} only (no internal details exposed).",
        "security": [],
        "responses": {
          "200": {
            "description": "System healthy",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": { "type": "string", "example": "healthy" },
                    "timestamp": { "type": "string", "format": "date-time" }
                  }
                }
              }
            }
          }
        }
      },
      "head": {
        "tags": ["Health"],
        "summary": "Health check (HEAD)",
        "security": [],
        "responses": {
          "200": { "description": "System healthy" }
        }
      }
    },
    "/config/pricing": {
      "get": {
        "tags": ["Config"],
        "summary": "Get pricing configuration",
        "description": "Returns plan pricing and per-workflow credit costs.",
        "security": [],
        "responses": {
          "200": { "description": "Pricing plans and workflow costs" }
        }
      }
    },
    "/config/studio": {
      "get": {
        "tags": ["Config"],
        "summary": "Get studio configuration",
        "description": "Returns available models, formats, and studio settings.",
        "security": [],
        "responses": {
          "200": { "description": "Studio configuration" }
        }
      }
    },
    "/contact": {
      "post": {
        "tags": ["Config"],
        "summary": "Submit contact form",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["email", "message"],
                "properties": {
                  "email": { "type": "string", "format": "email" },
                  "name": { "type": "string" },
                  "message": { "type": "string", "maxLength": 2000 }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Message sent" }
        }
      }
    },
    "/newsletter/subscribe": {
      "post": {
        "tags": ["Config"],
        "summary": "Subscribe to newsletter",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["email"],
                "properties": {
                  "email": { "type": "string", "format": "email" }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Subscribed" }
        }
      }
    },
    "/moderation/report": {
      "post": {
        "tags": ["Moderation"],
        "summary": "Report content",
        "description": "DSA-compliant content reporting.",
        "responses": {
          "200": { "description": "Report submitted" }
        }
      }
    },
    "/moderation/appeal": {
      "post": {
        "tags": ["Moderation"],
        "summary": "Appeal moderation decision",
        "responses": {
          "200": { "description": "Appeal submitted" }
        }
      }
    },
    "/notifications/subscribe": {
      "post": {
        "tags": ["Notifications"],
        "summary": "Subscribe to push notifications",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["subscription"],
                "properties": {
                  "subscription": { "type": "object", "description": "Web Push subscription object" }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Subscribed" }
        }
      },
      "delete": {
        "tags": ["Notifications"],
        "summary": "Unsubscribe from push notifications",
        "responses": {
          "200": { "description": "Unsubscribed" }
        }
      }
    },
    "/events/stream": {
      "get": {
        "tags": ["Notifications"],
        "summary": "System events stream (SSE)",
        "description": "Server-Sent Events for real-time system events (EventBus).",
        "responses": {
          "200": {
            "description": "SSE event stream",
            "content": { "text/event-stream": {} }
          }
        }
      }
    },
    "/voice/grok": {
      "get": {
        "tags": ["Chat"],
        "summary": "Get voice config",
        "responses": {
          "200": { "description": "Voice configuration" }
        }
      },
      "post": {
        "tags": ["Chat"],
        "summary": "Voice interaction",
        "description": "Process voice input for AI interaction.",
        "responses": {
          "200": { "description": "Voice response" }
        }
      }
    },
    "/checkout/payzone": {
      "post": {
        "tags": ["Billing"],
        "summary": "Create Payzone checkout session",
        "description": "Initialize payment via Payzone bridge (Morocco/MENA/Europe).",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["planId"],
                "properties": {
                  "planId": { "$ref": "#/components/schemas/PlanId" },
                  "interval": { "type": "string", "enum": ["monthly", "yearly"] }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Checkout URL returned" }
        }
      }
    },
    "/webhook/payzone": {
      "post": {
        "tags": ["Billing"],
        "summary": "Payzone webhook",
        "description": "Receives payment confirmation. HMAC SHA-256 signature verified. Idempotent (Redis NX).",
        "security": [],
        "responses": {
          "200": { "description": "Webhook processed" }
        }
      }
    },
    "/webhook/stripe": {
      "post": {
        "tags": ["Billing"],
        "summary": "Stripe webhook",
        "description": "Receives Stripe events. Signature verified. Idempotent (Redis NX).",
        "security": [],
        "responses": {
          "200": { "description": "Webhook processed" }
        }
      }
    },
    "/webhook/cmi": {
      "post": {
        "tags": ["Billing"],
        "summary": "CMI webhook (Morocco)",
        "description": "Receives CMI payment confirmation. HMAC signature verified.",
        "security": [],
        "responses": {
          "200": { "description": "Webhook processed" }
        }
      }
    },
    "/webhook/meta": {
      "get": {
        "tags": ["Notifications"],
        "summary": "Meta webhook verification",
        "description": "Handles Meta webhook challenge verification.",
        "security": [],
        "responses": {
          "200": { "description": "Challenge verified" }
        }
      },
      "post": {
        "tags": ["Notifications"],
        "summary": "Meta webhook events",
        "description": "Receives Meta platform events. HMAC signature verified.",
        "security": [],
        "responses": {
          "200": { "description": "Event processed" }
        }
      }
    },
    "/voice/grok/session": {
      "get": {
        "tags": ["Chat"],
        "summary": "Get voice session",
        "responses": {
          "200": { "description": "Voice session state" }
        }
      },
      "post": {
        "tags": ["Chat"],
        "summary": "Create voice session",
        "responses": {
          "200": { "description": "Voice session created" }
        }
      }
    },
    "/workflow/prefs": {
      "get": {
        "tags": ["Workflow"],
        "summary": "Get workflow preferences",
        "responses": {
          "200": { "description": "User workflow preferences" }
        }
      },
      "post": {
        "tags": ["Workflow"],
        "summary": "Save workflow preferences",
        "responses": {
          "200": { "description": "Preferences saved" }
        }
      }
    },
    "/export": {
      "get": {
        "tags": ["Projects"],
        "summary": "Export data",
        "responses": {
          "200": { "description": "Export data" }
        }
      },
      "post": {
        "tags": ["Projects"],
        "summary": "Create export job",
        "responses": {
          "200": { "description": "Export started" }
        }
      }
    },
    "/notifications/send": {
      "post": {
        "tags": ["Notifications"],
        "summary": "Send push notification",
        "description": "Send a push notification to a user.",
        "responses": {
          "200": { "description": "Notification sent" }
        }
      }
    },
    "/integrity": {
      "get": {
        "tags": ["Admin"],
        "summary": "System integrity check",
        "description": "Run system integrity verification. Admin only.",
        "responses": {
          "200": { "description": "Integrity check results" }
        }
      }
    },
    "/health/db": {
      "get": {
        "tags": ["Health"],
        "summary": "Database health check",
        "description": "Check database connectivity and response time.",
        "responses": {
          "200": { "description": "Database health status" }
        }
      }
    },
    "/health/signup-test": {
      "get": {
        "tags": ["Health"],
        "summary": "Signup flow test",
        "description": "Verify signup flow is operational.",
        "responses": {
          "200": { "description": "Signup test result" }
        }
      }
    },
    "/admin/users": {
      "get": {
        "tags": ["Admin"],
        "summary": "List all users",
        "description": "Admin only. Returns paginated user list.",
        "responses": {
          "200": { "description": "User list" },
          "403": { "description": "Admin access required" }
        }
      }
    },
    "/admin/users/{id}": {
      "get": {
        "tags": ["Admin"],
        "summary": "Get user details",
        "parameters": [
          { "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "User details" }
        }
      },
      "patch": {
        "tags": ["Admin"],
        "summary": "Update user",
        "parameters": [
          { "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "User updated" }
        }
      }
    },
    "/admin/users/{id}/status": {
      "patch": {
        "tags": ["Admin"],
        "summary": "Update user status",
        "description": "Activate or suspend a user account.",
        "parameters": [
          { "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["status"],
                "properties": {
                  "status": { "type": "string", "enum": ["active", "suspended"] }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Status updated" }
        }
      }
    },
    "/admin/users/{id}/credits": {
      "post": {
        "tags": ["Admin"],
        "summary": "Adjust user credits",
        "description": "Add or remove credits from a user account.",
        "parameters": [
          { "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["amount"],
                "properties": {
                  "amount": { "type": "integer", "description": "Positive to add, negative to remove" },
                  "reason": { "type": "string" }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Credits adjusted" }
        }
      }
    },
    "/admin/stats": {
      "get": {
        "tags": ["Admin"],
        "summary": "Platform statistics",
        "description": "Overall platform metrics: users, revenue, usage.",
        "responses": {
          "200": { "description": "Platform stats" }
        }
      }
    },
    "/admin/revenue": {
      "get": {
        "tags": ["Admin"],
        "summary": "Revenue analytics",
        "responses": {
          "200": { "description": "Revenue data with breakdown" }
        }
      }
    },
    "/admin/funnel": {
      "get": {
        "tags": ["Admin"],
        "summary": "Funnel analytics",
        "description": "Signup → Login → Studio → Generate → Purchase conversion funnel.",
        "responses": {
          "200": { "description": "Funnel data" }
        }
      }
    },
    "/admin/leads": {
      "get": {
        "tags": ["Admin"],
        "summary": "List leads",
        "responses": {
          "200": { "description": "Lead list" }
        }
      },
      "post": {
        "tags": ["Admin"],
        "summary": "Add lead",
        "responses": {
          "200": { "description": "Lead added" }
        }
      }
    },
    "/admin/moderation": {
      "get": {
        "tags": ["Admin"],
        "summary": "Moderation queue",
        "description": "View pending moderation items.",
        "responses": {
          "200": { "description": "Moderation queue" }
        }
      },
      "patch": {
        "tags": ["Admin"],
        "summary": "Resolve moderation item",
        "responses": {
          "200": { "description": "Item resolved" }
        }
      }
    },
    "/admin/agents": {
      "get": {
        "tags": ["Admin"],
        "summary": "List agents",
        "description": "Get orchestrator agent registry (4 agents).",
        "responses": {
          "200": { "description": "Agent registry" }
        }
      }
    },
    "/admin/agents/{agentId}/trigger": {
      "post": {
        "tags": ["Admin"],
        "summary": "Trigger agent",
        "description": "Manually trigger an orchestrator agent.",
        "parameters": [
          { "name": "agentId", "in": "path", "required": true, "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "Agent triggered" }
        }
      }
    },
    "/admin/settings": {
      "get": {
        "tags": ["Admin"],
        "summary": "Get system settings",
        "responses": {
          "200": { "description": "System settings" }
        }
      },
      "post": {
        "tags": ["Admin"],
        "summary": "Update system settings",
        "responses": {
          "200": { "description": "Settings updated" }
        }
      }
    },
    "/admin/system": {
      "get": {
        "tags": ["Admin"],
        "summary": "System status",
        "description": "Detailed system status: Redis, workers, queues, cron tasks.",
        "responses": {
          "200": { "description": "System status" }
        }
      }
    },
    "/admin/health": {
      "get": {
        "tags": ["Admin"],
        "summary": "Admin health dashboard",
        "description": "Detailed health check with service statuses (admin only).",
        "responses": {
          "200": { "description": "Detailed health status" }
        }
      }
    },
    "/admin/activity": {
      "get": {
        "tags": ["Admin"],
        "summary": "Activity log",
        "description": "Audit trail of user and system activities.",
        "responses": {
          "200": { "description": "Activity log entries" }
        }
      }
    },
    "/admin/reset-password": {
      "post": {
        "tags": ["Admin"],
        "summary": "Reset user password",
        "description": "Admin-initiated password reset for a user.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["userId"],
                "properties": {
                  "userId": { "type": "string" },
                  "newPassword": { "type": "string", "minLength": 8 }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Password reset" }
        }
      }
    },
    "/admin/marketing/generate": {
      "get": {
        "tags": ["Admin"],
        "summary": "Get marketing generation status",
        "responses": {
          "200": { "description": "Marketing generation status" }
        }
      },
      "post": {
        "tags": ["Admin"],
        "summary": "Trigger marketing content generation",
        "description": "Launch internal marketing workflows (blog, self-marketing, lead-gen).",
        "responses": {
          "200": { "description": "Generation triggered" }
        }
      }
    }
  }
}
