"""
REST API Paradigm - HTTP-based data access.
"""

import time
from typing import Dict, Any, List, Optional

from ..base import BaseQueryParadigm, QueryResult


class RESTAPIParadigm(BaseQueryParadigm):
    """REST API paradigm for HTTP-based data access."""

    @property
    def name(self) -> str:
        return "REST API"

    @property
    def description(self) -> str:
        return "HTTP-based data access using RESTful endpoints with standard HTTP methods and caching"

    @property
    def category(self) -> str:
        return "network"

    @property
    def complexity(self) -> str:
        return "intermediate"

    def execute(self, query: str, config: Dict[str, Any] = None) -> QueryResult:
        """Execute REST API request (not yet implemented)."""
        start_time = time.time()

        # This is a documentation paradigm - not yet implemented
        execution_time = (time.time() - start_time) * 1000

        return QueryResult(
            paradigm=self.name,
            query=query,
            execution_time_ms=execution_time,
            result_count=0,
            results=[],
            metadata={
                "status": "not_implemented",
                "implementation_issue": "TBD - to be created",
                "description": "REST API provides HTTP-based access to MarkiTect data with proper caching and pagination"
            },
            success=False,
            error_message="REST API paradigm not yet implemented. This paradigm will provide HTTP endpoints for data access."
        )

    def get_examples(self) -> List[Dict[str, str]]:
        """Get example REST API requests."""
        return [
            {
                "name": "List files",
                "description": "GET request to list all markdown files",
                "query": "GET /api/v1/files?type=markdown&limit=20"
            },
            {
                "name": "Search files",
                "description": "GET request with search parameters",
                "query": "GET /api/v1/files/search?q=documentation&author=Alice&tags=tutorial"
            },
            {
                "name": "Get file content",
                "description": "GET specific file with content",
                "query": "GET /api/v1/files/123?include=content,metadata,tags"
            },
            {
                "name": "Update file tags",
                "description": "PATCH request to update file tags",
                "query": "PATCH /api/v1/files/123/tags {'tags': ['updated', 'documentation']}"
            },
            {
                "name": "Bulk operations",
                "description": "POST request for bulk file operations",
                "query": "POST /api/v1/files/bulk {'action': 'add_tag', 'files': [1,2,3], 'tag': 'archived'}"
            }
        ]

    def validate_query(self, query: str) -> tuple[bool, Optional[str]]:
        """Validate REST API request format."""
        if not query.strip():
            return False, "REST API request cannot be empty"

        parts = query.strip().split(' ', 1)
        if len(parts) < 2:
            return False, "REST API request must include HTTP method and URL"

        method = parts[0].upper()
        valid_methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']

        if method not in valid_methods:
            return False, f"HTTP method must be one of: {', '.join(valid_methods)}"

        url = parts[1].split(' ')[0]
        if not url.startswith('/api/'):
            return False, "URL must start with /api/"

        return True, None

    def get_syntax_help(self) -> str:
        """Get syntax help for REST API requests."""
        return """REST API Request Syntax:

Format: <METHOD> <URL> [JSON_BODY]

HTTP Methods:
- GET: Retrieve data
- POST: Create new resources
- PUT: Update entire resource
- PATCH: Partial update
- DELETE: Remove resource

Base URL: /api/v1

Endpoints:
- /api/v1/files - File operations
- /api/v1/files/search - Search files
- /api/v1/files/{id} - Specific file operations
- /api/v1/tags - Tag operations
- /api/v1/authors - Author operations
- /api/v1/stats - Statistics

Query Parameters:
- limit: Limit number of results (default: 20, max: 100)
- offset: Skip number of results (for pagination)
- include: Comma-separated fields to include
- sort: Sort field (prefix with - for descending)
- filter[field]: Filter by field value

Examples:
GET /api/v1/files?limit=10&sort=-created_at
GET /api/v1/files/search?q=tutorial&filter[author]=Alice
POST /api/v1/files {"path": "/new/file.md", "content": "# New File"}
PATCH /api/v1/files/123 {"tags": ["updated"]}

Response Format:
{
  "data": [...],
  "meta": {
    "total": 100,
    "limit": 20,
    "offset": 0,
    "has_more": true
  }
}
"""