"""
Invoke deployed Cognite Functions from Python.

Use these helpers to call the data quality validation functions from a notebook,
script, or any Python runtime. Each function is a thin wrapper around
client.functions.call().
"""

from __future__ import annotations

from typing import Literal

from cognite.client import CogniteClient


def call_validation(
    client: CogniteClient,
    validation_type: Literal["instance", "partitioned", "timeseries", "orchestrator", "test"],
    data: dict,
    *,
    wait: bool = True,
    external_id: str = "data-quality-validation",
) -> dict:
    """Call the unified SHACL validation function.

    The unified function consolidates all validation types into a single deployment.
    Use this function for new code. Legacy individual functions are still supported.

    Args:
        client: Cognite client instance.
        validation_type: Type of validation to perform:
            - "instance": Basic instance validation (real-time)
            - "partitioned": Partitioned historic instance validation
            - "timeseries": Time series validation (normal/backfill)
            - "orchestrator": Historic validation orchestrator
            - "test": Test SHACL rules without writing to Records API
        data: Payload dict. Contents depend on validation_type.
        wait: If True, block until the function returns.
        external_id: Function external ID (default: data-quality-validation).

    Returns:
        Response dict from the appropriate handler.

    Example:
        # Instance validation
        result = call_validation(
            client=client,
            validation_type="instance",
            data={
                "instances": {"items": [...]},
                "shacl_rules_file_external_id": "my_rules",
                "datamodel_space": "my_space",
                "datamodel_external_id": "MyModel",
                "datamodel_version": "v1",
                "records_config": {...}
            }
        )

        # Orchestrator
        result = call_validation(
            client=client,
            validation_type="orchestrator",
            data={
                "datamodel_space": "my_space",
                "view_external_id": "MyView",
                "instance_space": "my_instances",
                ...
            }
        )
    """
    payload = {"validation_type": validation_type, **data}
    call = client.functions.call(external_id=external_id, data=payload, wait=wait)
    return call.get_response() or {}


def deploy_validation_pipeline(
    client: CogniteClient,
    data: dict | None = None,
    *,
    settings_path: str | None = None,
    views_dir: str | None = None,
    view_external_id: str | None = None,
    wait: bool = True,
    external_id: str = "data-quality-validation",
) -> dict:
    """Deploy and run a full validation pipeline with batch and incremental validation.

    This function:
    1. Triggers partitioned batch load of all instances (splits data into partitions)
    2. Sets up sync trigger for ongoing incremental validation
    3. Creates scheduled workflow for monitoring progress
    4. Continuously manages orchestration (retries, cleanup)

    Convenience wrapper for call_validation(validation_type="orchestrator", ...).

    Two usage modes:

    **Mode 1: Pass data dict directly (legacy):**
        deploy_validation_pipeline(client, data={...}, wait=True)

    **Mode 2: Load from YAML configs (recommended):**
        deploy_validation_pipeline(
            client,
            settings_path="config/environments/cog-sail/settings.yaml",
            view_external_id="SmallBoat",
            wait=True
        )

    Args:
        client: Cognite client instance.
        data: (Legacy) Payload dict. Typical keys: datamodel_space, datamodel_external_id,
            datamodel_version, view_space, view_external_id, view_version,
            instance_space, shacl_file_external_id, partition_count, partition_field,
            records_space, records_container, stream_id, rule_set_id, rule_set_version.
            If None, must provide settings_path.
        settings_path: Path to settings.yaml file. If provided, config will be loaded from YAML.
        views_dir: Directory containing view YAML configs. Defaults to settings_path parent / "views".
        view_external_id: Specific view to deploy. If None when using YAML mode, must provide data dict.
        wait: If True, block until the function returns.
        external_id: Function external ID (default: data-quality-validation).

    Returns:
        Response dict from the function.

    Example:
        # YAML mode (recommended)
        result = deploy_validation_pipeline(
            client,
            settings_path="config/environments/cog-sail/settings.yaml",
            view_external_id="SmallBoat",
        )

        # Legacy mode (still supported)
        result = deploy_validation_pipeline(
            client,
            data={"datamodel_space": "sailboat", ...}
        )
    """
    # If data dict is provided, use legacy mode
    if data is not None:
        return call_validation(client, "orchestrator", data, wait=wait, external_id=external_id)

    # YAML mode: load configuration from files
    if settings_path is None:
        raise ValueError("Must provide either 'data' dict or 'settings_path'")

    if view_external_id is None:
        raise ValueError("Must provide 'view_external_id' when using settings_path mode")

    from pathlib import Path

    import yaml

    from cognite_data_quality.deploy import ViewConfig, load_settings

    # Load settings
    settings_path_obj = Path(settings_path)
    settings = load_settings(settings_path_obj)
    base_dir = settings_path_obj.parent

    # Use function external_id from settings (overrides parameter default)
    function_external_id = settings.function.external_id

    # Load view config
    if views_dir is None:
        views_dir_obj = base_dir / "views"
    else:
        views_dir_obj = Path(views_dir) if not isinstance(views_dir, Path) else views_dir

    view_config: ViewConfig | None = None
    for config_file in views_dir_obj.glob("*.yaml"):
        config_data = yaml.safe_load(config_file.read_text(encoding="utf-8")) or {}
        config_data["_filename"] = config_file.name
        candidate = ViewConfig(**config_data)
        if candidate.view.external_id == view_external_id:
            view_config = candidate
            break

    if view_config is None:
        raise ValueError(
            f"View config for '{view_external_id}' not found in {views_dir_obj}. "
            f"Available views: {[f.stem for f in views_dir_obj.glob('*.yaml')]}"
        )

    # Build data dict from configs
    records = settings.records
    data = {
        "datamodel_space": view_config.view.space,
        "datamodel_external_id": view_config.view.external_id,
        "datamodel_version": view_config.view.version,
        "view_space": view_config.view.space,
        "view_external_id": view_config.view.external_id,
        "view_version": view_config.view.version,
        "instance_space": view_config.instance_space,
        "shacl_file_external_id": view_config.shacl_rules.external_id,
        "partition_count": view_config.partition_count,
        "partition_field": view_config.partition_field,
        "records_space": records.space,
        "records_container": records.container,
        "stream_id": records.stream_id,
        "rule_set_id": view_config.records.rule_set_id or f"{view_config.view.external_id}SHACL",
        "rule_set_version": view_config.records.rule_set_version or "1.0",
        "auto_load_depth": view_config.validation.auto_load_depth,
        "chunk_size": view_config.chunk_size,  # Instances per validation chunk
        "function_external_id": function_external_id,  # Pass function ID for orchestrator to use
        "data_quality_space": records.space,  # Use same space as records for orchestration state
        "max_retries": settings.partition_retries,
        "sync_batch_size": view_config.sync_batch_size
        if view_config.sync_batch_size is not None
        else (1000 if view_config.use_sync_cursor_mode else settings.trigger.batch_size),
        "sync_batch_timeout": settings.trigger.batch_timeout,
        "use_sync_cursor_mode": view_config.use_sync_cursor_mode,
    }

    # Compute sync_workflow_external_id using same pattern as deploy_instance_workflows
    # This ensures it matches the deployed workflow ID: {prefix}-{view_name}
    view_name = view_config.view.external_id.lower().replace("yourorg", "")
    sync_workflow_id = view_config.workflow_external_id or f"{settings.workflow.external_id_prefix}-{view_name}"
    data["sync_workflow_external_id"] = sync_workflow_id

    return call_validation(client, "orchestrator", data, wait=wait, external_id=function_external_id)


def call_validate_instances_shacl(
    client: CogniteClient,
    data: dict,
    *,
    wait: bool = True,
    external_id: str = "data-quality-validation",
) -> dict:
    """Call the instance SHACL validation function.

    Convenience wrapper for call_validation(validation_type="instance", ...).

    Args:
        client: Cognite client instance.
        data: Payload dict. Typical keys: instances (dict with items), shacl_rules or
            shacl_rules_file_external_id, datamodel_space, datamodel_external_id,
            datamodel_version, auto_load_depth, records_config (stream_id, rule_set_id, etc.).
        wait: If True, block until the function returns.
        external_id: Function external ID (default: data-quality-validation).

    Returns:
        Response dict with conforms, violations, instances_validated, etc.
    """
    return call_validation(client, "instance", data, wait=wait, external_id=external_id)


def call_validate_instances_shacl_partitioned(
    client: CogniteClient,
    data: dict,
    *,
    wait: bool = True,
    external_id: str = "data-quality-validation",
) -> dict:
    """Call the partitioned instance SHACL validation function (worker).

    Convenience wrapper for call_validation(validation_type="partitioned", ...).

    Args:
        client: Cognite client instance.
        data: Payload dict. Same shape as validate-instances-shacl; instances are
            typically provided by the orchestrator.
        wait: If True, block until the function returns.
        external_id: Function external ID (default: data-quality-validation).

    Returns:
        Response dict with status, conforms, violations, instances_validated, etc.
    """
    return call_validation(client, "partitioned", data, wait=wait, external_id=external_id)


def call_validate_timeseries_shacl(
    client: CogniteClient,
    data: dict,
    *,
    wait: bool = True,
    external_id: str = "data-quality-validation",
) -> dict:
    """Call the time series SHACL validation function.

    Convenience wrapper for call_validation(validation_type="timeseries", ...).

    Args:
        client: Cognite client instance.
        data: Payload dict. Typical keys: shacl_rules_file_external_id, datamodel_space,
            datamodel_external_id, datamodel_version, filter or instance_ids,
            records_config.
        wait: If True, block until the function returns.
        external_id: Function external ID (default: data-quality-validation).

    Returns:
        Response dict with validation results.
    """
    return call_validation(client, "timeseries", data, wait=wait, external_id=external_id)
