#!/usr/bin/env python3
"""
jq Query Strategy

This module implements the jq query strategy for jq JSON processor operations.

Company: eXonware.com
Author: Eng. Muhammad AlShehri
Email: connect@exonware.com
Version: 0.0.1.15
Generation Date: January 2, 2025
"""

from typing import Any, Dict, List, Optional
from .base import ADocumentQueryStrategy
from ...errors import XWNodeValueError
from ...contracts import QueryMode, QueryTrait


class JQStrategy(ADocumentQueryStrategy):
    """jq query strategy for jq JSON processor operations."""
    
    def __init__(self, **options):
        super().__init__(**options)
        self._mode = QueryMode.JQ
        self._traits = QueryTrait.DOCUMENT | QueryTrait.ANALYTICAL | QueryTrait.STREAMING
    
    def execute(self, query: str, **kwargs) -> Any:
        """Execute jq query."""
        if not self.validate_query(query):
            raise XWNodeValueError(f"Invalid jq query: {query}")
        return {"result": "jq query executed", "query": query}
    
    def validate_query(self, query: str) -> bool:
        """Validate jq query syntax."""
        if not query or not isinstance(query, str):
            return False
        return any(op in query for op in [".", "|", "select", "map", "filter", "group_by", "sort_by"])
    
    def get_query_plan(self, query: str) -> Dict[str, Any]:
        """Get jq query execution plan."""
        return {
            "query_type": "jq",
            "complexity": "MEDIUM",
            "estimated_cost": 60
        }
    
    def path_query(self, path: str) -> Any:
        """Execute path-based query."""
        return self.execute(f".{path}")
    
    def filter_query(self, filter_expression: str) -> Any:
        """Execute filter query."""
        return self.execute(f"select({filter_expression})")
    
    def projection_query(self, fields: List[str]) -> Any:
        """Execute projection query."""
        return self.execute(f"{{{', '.join(f'{field}: .{field}' for field in fields)}}}")
    
    def sort_query(self, sort_fields: List[str], order: str = "asc") -> Any:
        """Execute sort query."""
        return self.execute(f"sort_by(.{sort_fields[0]})")
    
    def limit_query(self, limit: int, offset: int = 0) -> Any:
        """Execute limit query."""
        return self.execute(f".[{offset}:{offset + limit}]")
