# flake8: noqa: E501
from cruxctl.common.api.rest_client import RestAPI


class CruxApiV4Ops(RestAPI):
    """
    https://api.cruxinformatics.com/v2/ops/swagger/ops-v2.json
    """

    def __init__(self, url, *args, **kwargs):
        kwargs.setdefault("api_root", "")
        kwargs.setdefault("api_version", "v4/ops")
        super().__init__(url, *args, **kwargs)

    def get_data_products(
        self,
        with_deleted=False,
        filter_query=None,
        sort_by=None,
        page_size=50,
        page_token=None,
        filter_by_org=False,
    ):
        """
        Gets a list of data products and cdu with filters
        See https://api.cruxinformatics.com/v2/ops/swagger#/data-products-v4/getV4OpsDataproducts
        :param with_deleted: Set to True to fetch Deleted data-products.
        :param filter_query: Fields used to filter data-products.
        :param sort_by: The definition to sort the results by
        :param page_size: The number of records per page
        :param page_token: The page token to start reading from
        :param filter_by_org:
        :return:
        Example
        ```
        {
          "items": [
            {
              "id": "Pr00CdejdvLC",
              "orgId": "OrAvzTFy",
              "ownerOrgId": "OrAvzTFy",
              "ownerOrgName": "Exchange Data International",
              "ownerOrgCode": "EDI",
              "subscriberOrg": "OrAvzTFy",
              "subscriberOrgCode": "EDI",
              "cduSubscriptionId": null,
              "consumerId": null,
              "supplierId": null,
              "supplierName": null,
              "datastoreId": null,
              "subscriptionType": "SUPPLIER",
              "cduId": "Cx20384",
              "connectionId": null,
              "destinationIds": [],
              "lastStep": null,
              "name": "EOD Pricing - Bonds - Dominican Republic Stock Exchange (XBVR)",
              "status": "DRAFT",
              "createdBy": "www.edi@edi.com",
              "createdAt": "2024-05-06T09:21:33.330+00:00",
              "modifiedAt": "2024-10-30T16:46:06.478+00:00",
              "averageMonthlyRows": 0,
              "code": "cx20384",
              "productFamily": "EDI - End-of-day Pricing Data | Bonds",
              "description": "The closing price is considered the most up-to-date, ... worldwide.",
              "shortDescription": null,
              "proprietaryDescription": null,
              "type": "Product",
              "sensitive": false,
              "common": false,
              "display": "true",
              "productStatus": "Done",
              "billingTier": null,
              "sourceCategory": null,
              "sourceType": "VENDOR",
              "marketVertical": "FINANCIAL",
              "assetClass": "FIXED INCOME",
              "region": "AMERICAS",
              "country": "DOMINICAN REPUBLIC",
              "jiraKey": "DS-40867",
              "mutualizable": "true",
              "dataCategory": "PRICE AND ANALYTICS",
              "attributes": {
                "discoverListing": false,
                "containsCusipSedol": false
              },
              "availability": "AVAILABLE_UPON_REQUEST",
              "datasetStateSummary": {
                "dataProductId": "Pr00CdejdvLC",
                "total": 1,
                "draft": 0,
                "testing": 0,
                "activating": 0,
                "active": 0,
                "deploy": 0,
                "deploying": 0
              },
              "deletedAt": null
            },
            ...
            ...
          ],
          "nextPageToken": "eyJkYXRlVGltZSI6IjIwMjUtMD...fQ",
          "previousPageToken": null,
          "kind": "DataProductCdu"
        }
        ```
        """

        params = {}
        if with_deleted is not None:
            params["withDeleted"] = with_deleted
        if filter_query:
            params["filters"] = filter_query
        if sort_by:
            params["sortBy"] = sort_by
        if page_size:
            params["pageSize"] = page_size
        if page_token:
            params["pageToken"] = page_token
        if filter_by_org is not None:
            params["filterByOrg"] = filter_by_org
        url = self.resource_url("data-products")
        return self.get(url, params=params)

    def iter_data_products_all(
        self,
        with_deleted=False,
        filter_query=None,
        sort_by="cduId",
        page_size=100,
        filter_by_org=False,
    ):
        """
        Gets a list of data products and cdu with filters
        See https://api.cruxinformatics.com/v2/ops/swagger#/data-products-v4/getV4OpsDataproducts
        :param with_deleted: Set to True to fetch Deleted data-products.
        :param filter_query: Fields used to filter data-products.
        :param sort_by: The definition to sort the results by
        :param page_size: The number of records per page
        :param filter_by_org:
        :return:
        """

        page_token = None
        while True:
            response = self.get_data_products(
                with_deleted=with_deleted,
                filter_query=filter_query,
                sort_by=sort_by,
                page_size=page_size,
                filter_by_org=filter_by_org,
                page_token=page_token,
            )
            if response is None:
                break
            items = response.get("items", []) if isinstance(response, dict) else []
            yield from items
            page_token = response.get("nextPageToken")
            if not page_token:
                break

    def get_data_product(self, pid, org_id=None, filter_by_org=False):
        """
        Gets data product and cdu by data product id or cdu id
        See https://api.cruxinformatics.com/v2/ops/swagger#/data-products-v4/getV4OpsDataproductsId
        :param pid: Data product identifier (e.g., Pr5L6KapZxKW)
        :param org_id: When passed returns FORGE data-product subscribed by the org.
        :param filter_by_org:
        :return:
        Example
        ```
        {
          "id": "Pr5L6KapZxKW",
          "orgId": "OrgvyxbY",
          "ownerOrgId": "OrgvyxbY",
          "ownerOrgName": "Morningstar",
          "ownerOrgCode": "MORN",
          "subscriberOrg": "OrgvyxbY",
          "subscriberOrgCode": "MORN",
          "cduSubscriptionId": null,
          "consumerId": null,
          "supplierId": null,
          "supplierName": null,
          "datastoreId": null,
          "subscriptionType": "SUPPLIER",
          "cduId": "Cx53683",
          "connectionId": null,
          "destinationIds": [],
          "lastStep": null,
          "name": "Purchase Details - Open End Fund - Hong Kong",
          "status": "DRAFT",
          "createdBy": "scott.vlna@morningstar.com",
          "createdAt": "2024-05-06T10:00:56.740+00:00",
          "modifiedAt": "2025-01-03T09:05:15.188+00:00",
          "averageMonthlyRows": 335191,
          "code": "cx53683",
          "productFamily": "Purchase Details",
          "description": "Provides data on the minimum and ... criteria and more.",
          "shortDescription": null,
          "proprietaryDescription": null,
          "type": "Product",
          "sensitive": false,
          "common": false,
          "display": "true",
          "productStatus": "Candidate",
          "billingTier": null,
          "sourceCategory": null,
          "sourceType": "VENDOR",
          "marketVertical": "FINANCIAL",
          "assetClass": "FUNDS",
          "region": "ASIA",
          "country": "CHINA, HONG KONG SPECIAL ADMINISTRATIVE REGION",
          "jiraKey": null,
          "mutualizable": "true",
          "dataCategory": "FUNDS",
          "attributes": {
            "containsCusipSedol": false
          },
          "availability": "AVAILABLE_UPON_REQUEST",
          "datasetStateSummary": {
            "dataProductId": "Pr5L6KapZxKW",
            "total": 1,
            "draft": 0,
            "testing": 0,
            "activating": 0,
            "active": 0,
            "deploy": 0,
            "deploying": 0
          },
          "deletedAt": null
        }
        ```
        """

        params = {}
        if org_id:
            params["orgId"] = org_id
        if filter_by_org is not None:
            params["filterByOrg"] = filter_by_org
        url = self.resource_url("data-products")
        return self.get(f"{url}/{pid}", params=params)

    def get_cdus(
        self,
        with_deleted=None,
        filter_query=None,
        sort_by=None,
        page_size=50,
        page_token=None,
        filter_by_org=False,
    ):
        """
        Gets a list of data products and cdu with filters
        See https://api.cruxinformatics.com/v2/ops/swagger#/data-products-v4/getV4OpsDataproducts
        :param with_deleted: Set to True to fetch Deleted data-products.
        :param filter_query: Fields used to filter data-products.
        :param sort_by: The definition to sort the results by
        :param page_size: The number of records per page
        :param page_token: The page token to start reading from
        :param filter_by_org:
        :return:
        Example
        ```
        {
          "items": [
            {
              "id": "Pr00CdejdvLC",
              "orgId": "OrAvzTFy",
              "ownerOrgId": "OrAvzTFy",
              "ownerOrgName": "Exchange Data International",
              "ownerOrgCode": "EDI",
              "subscriberOrg": "OrAvzTFy",
              "subscriberOrgCode": "EDI",
              "cduSubscriptionId": null,
              "consumerId": null,
              "supplierId": null,
              "supplierName": null,
              "datastoreId": null,
              "subscriptionType": "SUPPLIER",
              "cduId": "Cx20384",
              "connectionId": null,
              "destinationIds": [],
              "lastStep": null,
              "name": "EOD Pricing - Bonds - Dominican Republic Stock Exchange (XBVR)",
              "status": "DRAFT",
              "createdBy": "www.edi@edi.com",
              "createdAt": "2024-05-06T09:21:33.330+00:00",
              "modifiedAt": "2024-10-30T16:46:06.478+00:00",
              "averageMonthlyRows": 0,
              "code": "cx20384",
              "productFamily": "EDI - End-of-day Pricing Data | Bonds",
              "description": "The closing price is considered the most up-to-date, ... worldwide.",
              "shortDescription": null,
              "proprietaryDescription": null,
              "type": "Product",
              "sensitive": false,
              "common": false,
              "display": "true",
              "productStatus": "Done",
              "billingTier": null,
              "sourceCategory": null,
              "sourceType": "VENDOR",
              "marketVertical": "FINANCIAL",
              "assetClass": "FIXED INCOME",
              "region": "AMERICAS",
              "country": "DOMINICAN REPUBLIC",
              "jiraKey": "DS-40867",
              "mutualizable": "true",
              "dataCategory": "PRICE AND ANALYTICS",
              "attributes": {
                "discoverListing": false,
                "containsCusipSedol": false
              },
              "availability": "AVAILABLE_UPON_REQUEST",
              "datasetStateSummary": {
                "dataProductId": "Pr00CdejdvLC",
                "total": 1,
                "draft": 0,
                "testing": 0,
                "activating": 0,
                "active": 0,
                "deploy": 0,
                "deploying": 0
              },
              "deletedAt": null
            },
            ...
            ...
          ],
          "nextPageToken": "eyJkYXRlVGltZSI6IjIwMjUtMD...fQ",
          "previousPageToken": null,
          "kind": "DataProductCdu"
        }
        ```
        """

        return self.get_data_products(
            with_deleted=with_deleted,
            filter_query=filter_query,
            sort_by=sort_by,
            page_size=page_size,
            page_token=page_token,
            filter_by_org=filter_by_org,
        )

    def get_cdu(self, cdu_id, org_id=None, filter_by_org=False):
        """
        Gets data product and cdu by data product id or cdu id
        See https://api.cruxinformatics.com/v2/ops/swagger#/data-products-v4/getV4OpsDataproductsId
        :param cdu_id: Crux Delivery Unit identifier (e.g., Cx53683)
        :param org_id: When passed returns FORGE data-product subscribed by the org.
        :param filter_by_org:
        :return:
        Example
        ```
        {
          "id": "Pr5L6KapZxKW",
          "orgId": "OrgvyxbY",
          "ownerOrgId": "OrgvyxbY",
          "ownerOrgName": "Morningstar",
          "ownerOrgCode": "MORN",
          "subscriberOrg": "OrgvyxbY",
          "subscriberOrgCode": "MORN",
          "cduSubscriptionId": null,
          "consumerId": null,
          "supplierId": null,
          "supplierName": null,
          "datastoreId": null,
          "subscriptionType": "SUPPLIER",
          "cduId": "Cx53683",
          "connectionId": null,
          "destinationIds": [],
          "lastStep": null,
          "name": "Purchase Details - Open End Fund - Hong Kong",
          "status": "DRAFT",
          "createdBy": "scott.vlna@morningstar.com",
          "createdAt": "2024-05-06T10:00:56.740+00:00",
          "modifiedAt": "2025-01-03T09:05:15.188+00:00",
          "averageMonthlyRows": 335191,
          "code": "cx53683",
          "productFamily": "Purchase Details",
          "description": "Provides data on the minimum and ... criteria and more.",
          "shortDescription": null,
          "proprietaryDescription": null,
          "type": "Product",
          "sensitive": false,
          "common": false,
          "display": "true",
          "productStatus": "Candidate",
          "billingTier": null,
          "sourceCategory": null,
          "sourceType": "VENDOR",
          "marketVertical": "FINANCIAL",
          "assetClass": "FUNDS",
          "region": "ASIA",
          "country": "CHINA, HONG KONG SPECIAL ADMINISTRATIVE REGION",
          "jiraKey": null,
          "mutualizable": "true",
          "dataCategory": "FUNDS",
          "attributes": {
            "containsCusipSedol": false
          },
          "availability": "AVAILABLE_UPON_REQUEST",
          "datasetStateSummary": {
            "dataProductId": "Pr5L6KapZxKW",
            "total": 1,
            "draft": 0,
            "testing": 0,
            "activating": 0,
            "active": 0,
            "deploy": 0,
            "deploying": 0
          },
          "deletedAt": null
        }
        ```
        """

        return self.get_data_product(
            pid=cdu_id, org_id=org_id, filter_by_org=filter_by_org
        )

    def update_cdu(self, cdu_id, data, filter_by_org=False):
        """
        Gets data product and cdu by data product id or cdu id
        See https://api.cruxinformatics.com/v2/ops/swagger#/data-products-v4/getV4OpsDataproductsId
        :param cdu_id: Crux Delivery Unit identifier (e.g., Cx53683)
        :param data: CDU payload.
        :param filter_by_org:
        :return:
        Example
        ```
        {
          "id": "Pr5L6KapZxKW",
          "orgId": "OrgvyxbY",
          "ownerOrgId": "OrgvyxbY",
          "ownerOrgName": "Morningstar",
          "ownerOrgCode": "MORN",
          "subscriberOrg": "OrgvyxbY",
          "subscriberOrgCode": "MORN",
          "cduSubscriptionId": null,
          "consumerId": null,
          "supplierId": null,
          "supplierName": null,
          "datastoreId": null,
          "subscriptionType": "SUPPLIER",
          "cduId": "Cx53683",
          "connectionId": null,
          "destinationIds": [],
          "lastStep": null,
          "name": "Purchase Details - Open End Fund - Hong Kong",
          "status": "DRAFT",
          "createdBy": "scott.vlna@morningstar.com",
          "createdAt": "2024-05-06T10:00:56.740+00:00",
          "modifiedAt": "2025-01-03T09:05:15.188+00:00",
          "averageMonthlyRows": 335191,
          "code": "cx53683",
          "productFamily": "Purchase Details",
          "description": "Provides data on the minimum and ... criteria and more.",
          "shortDescription": null,
          "proprietaryDescription": null,
          "type": "Product",
          "sensitive": false,
          "common": false,
          "display": "true",
          "productStatus": "Candidate",
          "billingTier": null,
          "sourceCategory": null,
          "sourceType": "VENDOR",
          "marketVertical": "FINANCIAL",
          "assetClass": "FUNDS",
          "region": "ASIA",
          "country": "CHINA, HONG KONG SPECIAL ADMINISTRATIVE REGION",
          "jiraKey": null,
          "mutualizable": "true",
          "dataCategory": "FUNDS",
          "attributes": {
            "containsCusipSedol": false
          },
          "availability": "AVAILABLE_UPON_REQUEST",
          "datasetStateSummary": {
            "dataProductId": "Pr5L6KapZxKW",
            "total": 1,
            "draft": 0,
            "testing": 0,
            "activating": 0,
            "active": 0,
            "deploy": 0,
            "deploying": 0
          },
          "deletedAt": null
        }
        ```
        """

        params = {}
        if filter_by_org is not None:
            params["filterByOrg"] = filter_by_org
        url = self.resource_url("data-products")
        return self.patch(f"{url}/{cdu_id}", params=params, json=data)
