# #region SupersetDatasetsPreviewMixin [C:4] [TYPE Module] [SEMANTICS superset, dataset, preview, sample, review]
# @LAYER Infrastructure
# @BRIEF Dataset preview compilation mixin for SupersetClient — build query context, compile SQL.
# @RELATION DEPENDS_ON -> [SupersetClientBase]
# @RELATION DEPENDS_ON -> [SupersetDatasetsMixin]
from copy import deepcopy
import json
from typing import Any

from ..logger import belief_scope, logger as app_logger
from ..utils.network import SupersetAPIError


# #region SupersetDatasetsPreviewMixin [C:4] [TYPE Class]
# @BRIEF Mixin providing dataset preview compilation and query context building.
class SupersetDatasetsPreviewMixin:
    # #region SupersetClientCompileDatasetPreview [TYPE Function] [C:4]
    # @PURPOSE: Compile dataset preview SQL through the strongest supported Superset preview endpoint family and return normalized SQL output.
    def compile_dataset_preview(self, dataset_id: int, template_params: dict[str, Any] | None = None, effective_filters: list[dict[str, Any]] | None = None) -> dict[str, Any]:
        with belief_scope('SupersetClientCompileDatasetPreview'):
            app_logger.reason('Belief protocol reasoning checkpoint for SupersetClientCompileDatasetPreview')
            dataset_response = self.get_dataset(dataset_id)
            dataset_record = dataset_response.get('result', dataset_response) if isinstance(dataset_response, dict) else {}
            query_context = self.build_dataset_preview_query_context(dataset_id=dataset_id, dataset_record=dataset_record, template_params=template_params or {}, effective_filters=effective_filters or [])
            legacy_form_data = self.build_dataset_preview_legacy_form_data(dataset_id=dataset_id, dataset_record=dataset_record, template_params=template_params or {}, effective_filters=effective_filters or [])
            legacy_form_data_payload = json.dumps(legacy_form_data, sort_keys=True, default=str)
            request_payload = json.dumps(query_context)
            strategy_attempts: list[dict[str, Any]] = []
            strategy_candidates: list[dict[str, Any]] = [{'endpoint_kind': 'legacy_explore_form_data', 'endpoint': '/explore_json/form_data', 'request_transport': 'query_param_form_data', 'params': {'form_data': legacy_form_data_payload}}, {'endpoint_kind': 'legacy_data_form_data', 'endpoint': '/data', 'request_transport': 'query_param_form_data', 'params': {'form_data': legacy_form_data_payload}}, {'endpoint_kind': 'v1_chart_data', 'endpoint': '/chart/data', 'request_transport': 'json_body', 'data': request_payload, 'headers': {'Content-Type': 'application/json'}}]
            for candidate in strategy_candidates:
                endpoint_kind = candidate['endpoint_kind']
                endpoint_path = candidate['endpoint']
                request_transport = candidate['request_transport']
                request_params = deepcopy(candidate.get('params') or {})
                request_body = candidate.get('data')
                request_headers = deepcopy(candidate.get('headers') or {})
                request_param_keys = sorted(request_params.keys())
                request_payload_keys: list[str] = []
                if isinstance(request_body, str):
                    try:
                        decoded_request_body = json.loads(request_body)
                        if isinstance(decoded_request_body, dict):
                            request_payload_keys = sorted(decoded_request_body.keys())
                    except json.JSONDecodeError:
                        request_payload_keys = []
                elif isinstance(request_body, dict):
                    request_payload_keys = sorted(request_body.keys())
                strategy_diagnostics = {'endpoint': endpoint_path, 'endpoint_kind': endpoint_kind, 'request_transport': request_transport, 'contains_root_datasource': endpoint_kind == 'v1_chart_data' and 'datasource' in query_context, 'contains_form_datasource': endpoint_kind.startswith('legacy_') and 'datasource' in legacy_form_data, 'contains_query_object_datasource': bool(query_context.get('queries')) and isinstance(query_context['queries'][0], dict) and ('datasource' in query_context['queries'][0]), 'request_param_keys': request_param_keys, 'request_payload_keys': request_payload_keys}
                app_logger.reason('Attempting Superset dataset preview compilation strategy', extra={'dataset_id': dataset_id, **strategy_diagnostics, 'request_params': request_params, 'request_payload': request_body, 'legacy_form_data': legacy_form_data if endpoint_kind.startswith('legacy_') else None, 'query_context': query_context if endpoint_kind == 'v1_chart_data' else None, 'template_param_count': len(template_params or {}), 'filter_count': len(effective_filters or [])})
                try:
                    response = self.network.request(method='POST', endpoint=endpoint_path, params=request_params or None, data=request_body, headers=request_headers or None)
                    normalized = self._extract_compiled_sql_from_preview_response(response)
                    normalized['query_context'] = query_context
                    normalized['legacy_form_data'] = legacy_form_data
                    normalized['endpoint'] = endpoint_path
                    normalized['endpoint_kind'] = endpoint_kind
                    normalized['dataset_id'] = dataset_id
                    normalized['strategy_attempts'] = strategy_attempts + [{**strategy_diagnostics, 'success': True}]
                    app_logger.reflect('Dataset preview compilation returned normalized SQL payload', extra={'dataset_id': dataset_id, **strategy_diagnostics, 'success': True, 'compiled_sql_length': len(str(normalized.get('compiled_sql') or '')), 'response_diagnostics': normalized.get('response_diagnostics')})
                    app_logger.reflect('Belief protocol postcondition checkpoint for SupersetClientCompileDatasetPreview')
                    return normalized
                except Exception as exc:
                    failure_diagnostics = {**strategy_diagnostics, 'success': False, 'error': str(exc)}
                    strategy_attempts.append(failure_diagnostics)
                    app_logger.explore('Superset dataset preview compilation strategy failed', extra={'dataset_id': dataset_id, **failure_diagnostics, 'request_params': request_params, 'request_payload': request_body})
            raise SupersetAPIError(f'Superset preview compilation failed for all known strategies (attempts={strategy_attempts!r})')
    # #endregion SupersetClientCompileDatasetPreview
    # #region SupersetClientBuildDatasetPreviewLegacyFormData [TYPE Function] [C:4]
    # @PURPOSE: Build browser-style legacy form_data payload for Superset preview endpoints inferred from observed deployment traffic.
    def build_dataset_preview_legacy_form_data(self, dataset_id: int, dataset_record: dict[str, Any], template_params: dict[str, Any], effective_filters: list[dict[str, Any]]) -> dict[str, Any]:
        with belief_scope('SupersetClientBuildDatasetPreviewLegacyFormData'):
            app_logger.reason('Belief protocol reasoning checkpoint for SupersetClientBuildDatasetPreviewLegacyFormData')
            query_context = self.build_dataset_preview_query_context(dataset_id=dataset_id, dataset_record=dataset_record, template_params=template_params, effective_filters=effective_filters)
            query_object = deepcopy(query_context.get('queries', [{}])[0] if query_context.get('queries') else {})
            legacy_form_data = deepcopy(query_context.get('form_data', {}))
            legacy_form_data.pop('datasource', None)
            legacy_form_data['metrics'] = deepcopy(query_object.get('metrics', ['count']))
            legacy_form_data['columns'] = deepcopy(query_object.get('columns', []))
            legacy_form_data['orderby'] = deepcopy(query_object.get('orderby', []))
            legacy_form_data['annotation_layers'] = deepcopy(query_object.get('annotation_layers', []))
            legacy_form_data['row_limit'] = query_object.get('row_limit', 1000)
            legacy_form_data['series_limit'] = query_object.get('series_limit', 0)
            legacy_form_data['url_params'] = deepcopy(query_object.get('url_params', template_params))
            legacy_form_data['applied_time_extras'] = deepcopy(query_object.get('applied_time_extras', {}))
            legacy_form_data['result_format'] = query_context.get('result_format', 'json')
            legacy_form_data['result_type'] = query_context.get('result_type', 'query')
            legacy_form_data['force'] = bool(query_context.get('force', True))
            extras = query_object.get('extras')
            if isinstance(extras, dict):
                legacy_form_data['extras'] = deepcopy(extras)
            time_range = query_object.get('time_range')
            if time_range:
                legacy_form_data['time_range'] = time_range
            app_logger.reflect('Built Superset legacy preview form_data payload from browser-observed request shape', extra={'dataset_id': dataset_id, 'legacy_endpoint_inference': 'POST /explore_json/form_data?form_data=... primary, POST /data?form_data=... fallback, based on observed browser traffic', 'contains_form_datasource': 'datasource' in legacy_form_data, 'legacy_form_data_keys': sorted(legacy_form_data.keys()), 'legacy_extra_filters': legacy_form_data.get('extra_filters', []), 'legacy_extra_form_data': legacy_form_data.get('extra_form_data', {})})
            app_logger.reflect('Belief protocol postcondition checkpoint for SupersetClientBuildDatasetPreviewLegacyFormData')
            return legacy_form_data
    # #endregion SupersetClientBuildDatasetPreviewLegacyFormData
    # #region SupersetClientBuildDatasetPreviewQueryContext [TYPE Function] [C:4]
    # @PURPOSE: Build a reduced-scope chart-data query context for deterministic dataset preview compilation.
    def build_dataset_preview_query_context(
        self,
        dataset_id: int,
        dataset_record: dict[str, Any],
        template_params: dict[str, Any],
        effective_filters: list[dict[str, Any]],
    ) -> dict[str, Any]:
        with belief_scope("SupersetClientBuildDatasetPreviewQueryContext"):
            app_logger.reason(
                "Building Superset dataset preview query context",
                extra={"dataset_id": dataset_id, "filter_count": len(effective_filters or [])},
            )
            normalized_template_params = deepcopy(template_params or {})
            normalized_filter_payload = (
                self._normalize_effective_filters_for_query_context(
                    effective_filters or []
                )
            )
            normalized_filters = normalized_filter_payload["filters"]
            normalized_extra_form_data = normalized_filter_payload["extra_form_data"]
            datasource_payload: dict[str, Any] = {
                "id": dataset_id,
                "type": "table",
            }
            datasource = dataset_record.get("datasource")
            if isinstance(datasource, dict):
                datasource_id = datasource.get("id")
                datasource_type = datasource.get("type")
                if datasource_id is not None:
                    datasource_payload["id"] = datasource_id
                if datasource_type:
                    datasource_payload["type"] = datasource_type
            serialized_dataset_template_params = dataset_record.get("template_params")
            if (
                isinstance(serialized_dataset_template_params, str)
                and serialized_dataset_template_params.strip()
            ):
                try:
                    parsed_dataset_template_params = json.loads(
                        serialized_dataset_template_params
                    )
                    if isinstance(parsed_dataset_template_params, dict):
                        for key, value in parsed_dataset_template_params.items():
                            normalized_template_params.setdefault(str(key), value)
                except json.JSONDecodeError:
                    app_logger.explore(
                        "Dataset template_params could not be parsed while building preview query context",
                        extra={"dataset_id": dataset_id},
                    )
            extra_form_data: dict[str, Any] = deepcopy(normalized_extra_form_data)
            if normalized_filters:
                extra_form_data["filters"] = deepcopy(normalized_filters)
            query_object: dict[str, Any] = {
                "filters": normalized_filters,
                "extras": {"where": ""},
                "columns": [],
                "metrics": ["count"],
                "orderby": [],
                "annotation_layers": [],
                "row_limit": 1000,
                "series_limit": 0,
                "url_params": normalized_template_params,
                "applied_time_extras": {},
                "result_type": "query",
            }
            schema = dataset_record.get("schema")
            if schema:
                query_object["schema"] = schema
            time_range = extra_form_data.get("time_range") or dataset_record.get(
                "default_time_range"
            )
            if time_range:
                query_object["time_range"] = time_range
                extra_form_data["time_range"] = time_range
            result_format = dataset_record.get("result_format") or "json"
            result_type = "query"
            form_data: dict[str, Any] = {
                "datasource": f"{datasource_payload['id']}__{datasource_payload['type']}",
                "datasource_id": datasource_payload["id"],
                "datasource_type": datasource_payload["type"],
                "viz_type": "table",
                "slice_id": None,
                "query_mode": "raw",
                "url_params": normalized_template_params,
                "extra_filters": deepcopy(normalized_filters),
                "adhoc_filters": [],
            }
            if extra_form_data:
                form_data["extra_form_data"] = extra_form_data
            payload = {
                "datasource": datasource_payload,
                "queries": [query_object],
                "form_data": form_data,
                "result_format": result_format,
                "result_type": result_type,
                "force": True,
            }
            app_logger.reflect(
                "Built Superset dataset preview query context",
                extra={
                    "dataset_id": dataset_id,
                    "datasource": datasource_payload,
                    "normalized_effective_filters": normalized_filters,
                    "normalized_filter_diagnostics": normalized_filter_payload[
                        "diagnostics"
                    ],
                    "result_type": result_type,
                    "result_format": result_format,
                },
            )
            return payload
    # #endregion SupersetClientBuildDatasetPreviewQueryContext
# #endregion SupersetDatasetsPreviewMixin
# #endregion SupersetDatasetsPreviewMixin
