File size: 15,093 Bytes
a74b879
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
"""
API Documentation System
- OpenAPI/Swagger documentation
- Endpoint discovery
- Schema validation
"""

from fastapi.openapi.utils import get_openapi
from fastapi import FastAPI
import json
from typing import Dict, List, Any, Optional
from pathlib import Path
import os

class APIDocumentation:
    """API documentation generator"""
    
    @staticmethod
    def generate_openapi_schema(app: FastAPI) -> Dict[str, Any]:
        """Generate OpenAPI schema"""
        return get_openapi(
            title="Moharek GEO Platform API",
            version="1.0.0",
            description="AI-powered Generative Engine Optimization platform",
            routes=app.routes,
        )
    
    @staticmethod
    def get_endpoint_docs() -> List[Dict[str, Any]]:
        """Get documentation for all endpoints"""
        return [
            {
                "path": "/api/crawl",
                "method": "POST",
                "description": "Crawl website and analyze content",
                "parameters": {
                    "url": "Website URL to crawl",
                    "org_name": "Organization name",
                    "org_url": "Organization URL",
                    "max_pages": "Maximum pages to crawl (default: 3)",
                    "runs": "Number of runs to average (default: 1)"
                },
                "response": {
                    "ok": "Success status",
                    "message": "Response message",
                    "mean_score": "Average GEO score",
                    "median_score": "Median GEO score",
                    "variance": "Score variance"
                },
                "rate_limit": "10 requests/hour",
                "authentication": "Optional (Bearer token)"
            },
            {
                "path": "/api/jobs",
                "method": "POST",
                "description": "Enqueue a crawl job",
                "parameters": {
                    "url": "Website URL",
                    "org_name": "Organization name",
                    "org_url": "Organization URL",
                    "max_pages": "Maximum pages (default: 3)",
                    "runs": "Number of runs (default: 1)"
                },
                "response": {
                    "ok": "Success status",
                    "job_id": "Job ID for tracking"
                },
                "rate_limit": "30 requests/minute",
                "authentication": "Optional"
            },
            {
                "path": "/api/jobs/{job_id}",
                "method": "GET",
                "description": "Get job status",
                "parameters": {
                    "job_id": "Job ID"
                },
                "response": {
                    "ok": "Success status",
                    "job": "Job details including status and progress"
                },
                "rate_limit": "100 requests/minute",
                "authentication": "Optional"
            },
            {
                "path": "/ws/jobs/{job_id}",
                "method": "WebSocket",
                "description": "Real-time job progress updates",
                "parameters": {
                    "job_id": "Job ID"
                },
                "response": "Job status updates in real-time",
                "rate_limit": "Unlimited",
                "authentication": "Optional"
            },
            {
                "path": "/api/analyze",
                "method": "POST",
                "description": "Analyze crawled content",
                "parameters": {
                    "job_id": "Job ID (optional)",
                    "api_keys": "API keys for external services"
                },
                "response": {
                    "ok": "Success status",
                    "analysis": "Content analysis results",
                    "geo_score": "GEO visibility score",
                    "competitor_insight": "Competitor analysis"
                },
                "rate_limit": "20 requests/hour",
                "authentication": "Optional"
            },
            {
                "path": "/api/recommendations",
                "method": "POST",
                "description": "Generate SEO recommendations",
                "parameters": {
                    "job_id": "Job ID (optional)",
                    "api_keys": "API keys for external services"
                },
                "response": {
                    "ok": "Success status",
                    "recommendations": "List of recommendations",
                    "audit": "Audit data",
                    "geo_score": "GEO score"
                },
                "rate_limit": "20 requests/hour",
                "authentication": "Optional"
            },
            {
                "path": "/api/keywords",
                "method": "POST",
                "description": "Extract and analyze keywords",
                "parameters": {
                    "url": "Website URL",
                    "max_pages": "Maximum pages (default: 1)",
                    "enrich": "Enrich with search volume data",
                    "analytics": "Return analytics data"
                },
                "response": {
                    "ok": "Success status",
                    "keywords": "List of keywords",
                    "analytics": "Keyword analytics (if requested)"
                },
                "rate_limit": "15 requests/hour",
                "authentication": "Optional"
            },
            {
                "path": "/api/content/generate",
                "method": "POST",
                "description": "Generate AI content",
                "parameters": {
                    "keyword": "Target keyword",
                    "lang": "Language (default: en)",
                    "target_site": "Target website",
                    "prefer_backend": "AI backend (groq/openai)"
                },
                "response": {
                    "ok": "Success status",
                    "result": "Generated content"
                },
                "rate_limit": "5 requests/hour",
                "authentication": "Optional"
            },
            {
                "path": "/api/content/optimize",
                "method": "POST",
                "description": "Optimize existing content",
                "parameters": {
                    "content": "Content to optimize",
                    "keyword": "Target keyword",
                    "lang": "Language (default: en)"
                },
                "response": {
                    "ok": "Success status",
                    "result": "Optimized content"
                },
                "rate_limit": "10 requests/hour",
                "authentication": "Optional"
            },
            {
                "path": "/api/users/register",
                "method": "POST",
                "description": "Register new user",
                "parameters": {
                    "email": "User email",
                    "password": "User password",
                    "company_id": "Company ID (optional)"
                },
                "response": {
                    "ok": "Success status",
                    "user_id": "New user ID",
                    "token": "Authentication token"
                },
                "rate_limit": "5 requests/minute",
                "authentication": "None"
            },
            {
                "path": "/api/users/login",
                "method": "POST",
                "description": "Login user",
                "parameters": {
                    "email": "User email",
                    "password": "User password"
                },
                "response": {
                    "ok": "Success status",
                    "token": "Authentication token",
                    "user": "User details"
                },
                "rate_limit": "10 requests/minute",
                "authentication": "None"
            },
            {
                "path": "/api/users/me",
                "method": "GET",
                "description": "Get current user",
                "parameters": {},
                "response": {
                    "ok": "Success status",
                    "user": "User details"
                },
                "rate_limit": "100 requests/minute",
                "authentication": "Required (Bearer token)"
            },
            {
                "path": "/api/notifications",
                "method": "GET",
                "description": "Get user notifications",
                "parameters": {
                    "unread_only": "Only unread notifications"
                },
                "response": {
                    "ok": "Success status",
                    "notifications": "List of notifications",
                    "count": "Total count"
                },
                "rate_limit": "50 requests/minute",
                "authentication": "Required"
            },
            {
                "path": "/api/2fa/setup",
                "method": "POST",
                "description": "Setup two-factor authentication",
                "parameters": {},
                "response": {
                    "ok": "Success status",
                    "secret": "2FA secret",
                    "qr_code": "QR code for authenticator app"
                },
                "rate_limit": "5 requests/minute",
                "authentication": "Required"
            },
            {
                "path": "/api/support/tickets",
                "method": "POST",
                "description": "Create support ticket",
                "parameters": {
                    "subject": "Ticket subject",
                    "description": "Ticket description",
                    "category": "Ticket category",
                    "priority": "Priority level"
                },
                "response": {
                    "ok": "Success status",
                    "ticket_id": "New ticket ID"
                },
                "rate_limit": "10 requests/hour",
                "authentication": "Required"
            },
            {
                "path": "/api/ads/dashboard",
                "method": "GET",
                "description": "Get ads dashboard data",
                "parameters": {
                    "demo": "Use demo data",
                    "days": "Number of days (default: 30)"
                },
                "response": {
                    "ok": "Success status",
                    "summary": "KPI summary",
                    "campaigns": "Campaign data"
                },
                "rate_limit": "20 requests/hour",
                "authentication": "Optional"
            },
            {
                "path": "/api/geo/visibility",
                "method": "POST",
                "description": "Check AI visibility score",
                "parameters": {
                    "brand": "Brand name",
                    "queries": "Search queries",
                    "api_keys": "API keys"
                },
                "response": {
                    "ok": "Success status",
                    "result": "Visibility score and details"
                },
                "rate_limit": "20 requests/hour",
                "authentication": "Optional"
            },
            {
                "path": "/health",
                "method": "GET",
                "description": "Health check endpoint",
                "parameters": {},
                "response": {
                    "status": "Service status",
                    "service": "Service name"
                },
                "rate_limit": "Unlimited",
                "authentication": "None"
            }
        ]
    
    @staticmethod
    def get_error_codes() -> Dict[str, str]:
        """Get error code documentation"""
        return {
            "200": "OK - Request successful",
            "201": "Created - Resource created successfully",
            "400": "Bad Request - Invalid parameters",
            "401": "Unauthorized - Authentication required",
            "403": "Forbidden - Insufficient permissions",
            "404": "Not Found - Resource not found",
            "429": "Too Many Requests - Rate limit exceeded",
            "500": "Internal Server Error - Server error",
            "503": "Service Unavailable - Service temporarily unavailable"
        }
    
    @staticmethod
    def get_authentication_docs() -> Dict[str, Any]:
        """Get authentication documentation"""
        return {
            "methods": [
                {
                    "type": "Bearer Token",
                    "description": "JWT token in Authorization header",
                    "example": "Authorization: Bearer <token>",
                    "endpoints": "Most endpoints"
                },
                {
                    "type": "API Key",
                    "description": "API key for external services",
                    "example": "api_keys: {openai: <key>, groq: <key>}",
                    "endpoints": "Content generation, analysis"
                }
            ],
            "token_expiry": "24 hours",
            "refresh": "Login again to get new token"
        }
    
    @staticmethod
    def get_rate_limit_docs() -> Dict[str, Any]:
        """Get rate limit documentation"""
        return {
            "default": "100 requests/minute",
            "endpoints": {
                "/api/crawl": "10 requests/hour",
                "/api/analyze": "20 requests/hour",
                "/api/keywords": "15 requests/hour",
                "/api/content/generate": "5 requests/hour",
                "/api/search": "30 requests/hour"
            },
            "headers": {
                "X-RateLimit-Limit": "Maximum requests allowed",
                "X-RateLimit-Remaining": "Remaining requests",
                "Retry-After": "Seconds to wait before retry"
            },
            "exceeded": "Returns 429 status code"
        }
    
    @staticmethod
    def save_documentation(output_path: str = None):
        """Save documentation to file"""
        if not output_path:
            output_path = Path(os.environ.get('OUTPUT_DIR', './output')) / 'api_docs.json'
        
        docs = {
            "title": "Moharek GEO Platform API",
            "version": "1.0.0",
            "description": "AI-powered Generative Engine Optimization platform",
            "endpoints": APIDocumentation.get_endpoint_docs(),
            "error_codes": APIDocumentation.get_error_codes(),
            "authentication": APIDocumentation.get_authentication_docs(),
            "rate_limits": APIDocumentation.get_rate_limit_docs()
        }
        
        Path(output_path).write_text(json.dumps(docs, indent=2))
        return output_path

# Generate documentation on import
try:
    APIDocumentation.save_documentation()
except Exception as e:
    print(f"Warning: Could not save API documentation: {e}")