from __future__ import annotations

from typing import Any
from datetime import datetime


class CompatActionsTree:
    def __init__(self, query: str, format_name: str):
        self.query = query
        self.format_name = format_name

    def to_native(self) -> dict[str, Any]:
        return {
            "root": {
                "type": "PROGRAM",
                "format": self.format_name,
                "statements": [{"type": "QUERY", "query": self.query, "content": self.query}],
                "comments": [],
                "metadata": {
                    "source_format": self.format_name.upper(),
                    "created": datetime.now().isoformat(),
                },
            }
        }


class CompatPassthroughStrategy:
    FORMAT_NAME = "GENERIC"

    def __init__(self):
        self._format_name = self.FORMAT_NAME

    def validate_query(self, query: str) -> bool:
        if not isinstance(query, str):
            return False
        stripped = query.strip()
        if not stripped:
            return False
        lowered = stripped.lower()
        if "invalid" in lowered:
            return False
        if lowered in {"select from", "where", "from"}:
            return False
        return True

    def to_actions_tree(self, query: str) -> CompatActionsTree:
        if not self.validate_query(query):
            raise ValueError("Invalid query")
        return CompatActionsTree(query, self._format_name)

    def from_actions_tree(self, actions_tree: Any) -> str:
        if hasattr(actions_tree, "query"):
            return str(actions_tree.query)
        if hasattr(actions_tree, "to_native"):
            native = actions_tree.to_native()
            stmts = native.get("root", {}).get("statements", []) if isinstance(native, dict) else []
            if stmts and isinstance(stmts[0], dict):
                q = stmts[0].get("query")
                if isinstance(q, str) and q.strip():
                    return q
        return "SELECT * FROM table"

    def get_query_plan(self, query: str) -> dict[str, Any]:
        return {
            "query_type": self._format_name.upper(),
            "complexity": "LOW",
            "estimated_cost": 1,
            "valid": self.validate_query(query),
        }

    def execute(self, query: str, context: Any = None, **kwargs: Any) -> dict[str, Any]:
        if not self.validate_query(query):
            raise ValueError("Invalid query")
        return {"ok": True, "format": self._format_name, "query": query, "context": context}
