from pathlib import Path
from unittest.mock import MagicMock

import pytest

from cognite_toolkit._cdf_tk.commands.deploy import DeployCommand
from cognite_toolkit._cdf_tk.cruds import ResourceWorker, ViewCRUD
from cognite_toolkit._cdf_tk.utils.auth import EnvironmentVariables


class TestDeployCommand:
    def test_load_files(self, env_vars_with_client: EnvironmentVariables) -> None:
        path = MagicMock(spec=Path)
        path.name = "my.View.yaml"
        path.read_text.return_value = VIEW_SOURCE_NONE
        worker = ResourceWorker(ViewCRUD.create_loader(env_vars_with_client.get_client()), "deploy")

        with pytest.raises(TypeError) as e:
            worker.prepare_resources([path], environment_variables={}, is_dry_run=True, verbose=False)

        assert e.value

    def test_track_module_deploy(self, tmp_path: Path) -> None:
        with (tmp_path / "_build_environment.yaml").open("w") as f:
            f.write("""# DO NOT EDIT THIS FILE!
name: dev
project: my_project
validation-type: dev
selected:
- modules/
cdf_toolkit_version: 0.0.0
read_modules:
- dir: cognite_toolkit/modules/custom/my_module
  resource_directories:
  - data_sets
  module_id: data_model
  package_id: rmdm
- dir: cognite_toolkit/modules/custom/my_module
  resource_directories:
  - data_sets
  module_id: agent
  package_id: rmdm
""")

        cmd = DeployCommand(print_warning=True, skip_tracking=True)
        cmd.deploy_build_directory(
            env_vars=EnvironmentVariables(
                CDF_PROJECT="my_project",
                CDF_CLUSTER="my_cluster",
                IDP_CLIENT_ID="my_client_id",
                IDP_CLIENT_SECRET="my_client_secret",
                IDP_TENANT_ID="my_tenant_id",
            ),
            build_dir=tmp_path,
            build_env_name="dev",
            dry_run=False,
            drop=False,
            drop_data=False,
            force_update=False,
            include=None,
            verbose=False,
        )

        assert cmd._additional_tracking_info.project == "my_project"
        assert cmd._additional_tracking_info.cluster == "my_cluster"
        assert cmd._additional_tracking_info.package_ids == {"rmdm"}
        assert cmd._additional_tracking_info.module_ids == {"agent", "data_model"}


VIEW_SOURCE_NONE = """- space: dm_domain_generic
  externalId: Equipment
  name: Equipment
  version: v1
  properties:
    id:
      container:
        space: dm_domain_generic
        externalId: Tag
      containerPropertyIdentifier: id
      type:
        list: false
        collation: ucs_basic
        type: text
      source:
"""
