"""Licensing API endpoints.

This file is automatically @generated from the Meraki API specification.
Do not edit this file manually.

"""

from __future__ import annotations

import urllib.parse
from typing import TYPE_CHECKING, Any, Literal

from meraki_client.schemas import (
    BindAdministeredLicensingSubscriptionSubscriptionResponse,
    ClaimAdministeredLicensingSubscriptionSubscriptionsResponse,
    GetAdministeredLicensingSubscriptionEntitlementsResponseItem,
    GetAdministeredLicensingSubscriptionSubscriptionsComplianceStatusesResponseItem,
    GetAdministeredLicensingSubscriptionSubscriptionsResponseItem,
    GetOrganizationLicensingCotermLicensesResponseItem,
    MoveOrganizationLicensingCotermLicensesDestination,
    MoveOrganizationLicensingCotermLicensesLicensesItem,
    MoveOrganizationLicensingCotermLicensesResponse,
    ValidateAdministeredLicensingSubscriptionSubscriptionsClaimKeyResponse,
)
from meraki_client.types import (
    GetAdministeredLicensingSubscriptionSubscriptionsProductTypes,
    GetAdministeredLicensingSubscriptionSubscriptionsStatuses,
)

if TYPE_CHECKING:
    from meraki_client._session import PaginatedResponse, Session


class Licensing:
    """Licensing class."""

    def __init__(self, session: Session) -> None:
        self._session = session

    def get_administered_licensing_subscription_entitlements(
        self, *, skus: list[str] | None = None
    ) -> PaginatedResponse[GetAdministeredLicensingSubscriptionEntitlementsResponseItem]:
        """Retrieve the list of purchasable entitlements.

        [API documentation: getAdministeredLicensingSubscriptionEntitlements](https://developer.cisco.com/meraki/api-v1/#!get-administered-licensing-subscription-entitlements)

        Args:
            skus: Filter to entitlements with the specified SKUs.

        Returns:
            Successful operation.

        Note:
            Returns a lazy PaginatedResponse
            that can be iterated or collected with `.collect()`.
            Page metadata is available on `.meta` and `.meta_pages`.

        Example API response:
            ```json
            {
              "sku": "LIC-MR-A",
              "name": "MR",
              "productType": "wireless",
              "productClass": "MR",
              "featureTier": "advantage",
              "isAddOn": false,
              "isFree": false
            }
            ```

        """
        path = f"/administered/licensing/subscription/entitlements"

        params: dict[str, Any] = {}
        if skus is not None:
            params["skus[]"] = skus

        return self._session.get_pages(
            scope="licensing",
            operation_id="getAdministeredLicensingSubscriptionEntitlements",
            path=path,
            params=params,
            item_schema=GetAdministeredLicensingSubscriptionEntitlementsResponseItem,
        )

    def get_administered_licensing_subscription_subscriptions(
        self,
        organization_ids: list[str],
        *,
        per_page: int | None = None,
        starting_after: str | None = None,
        ending_before: str | None = None,
        subscription_ids: list[str] | None = None,
        statuses: GetAdministeredLicensingSubscriptionSubscriptionsStatuses | None = None,
        product_types: GetAdministeredLicensingSubscriptionSubscriptionsProductTypes | None = None,
        skus: list[str] | None = None,
        name: str | None = None,
        start_date: str | None = None,
        end_date: str | None = None,
        total_pages: int | Literal["all"] = "all",
        direction: Literal["prev", "next"] = "next",
    ) -> PaginatedResponse[GetAdministeredLicensingSubscriptionSubscriptionsResponseItem]:
        """List available subscriptions.

        [API documentation: getAdministeredLicensingSubscriptionSubscriptions](https://developer.cisco.com/meraki/api-v1/#!get-administered-licensing-subscription-subscriptions)

        Args:
            per_page: The number of entries per page returned. Acceptable range is 3 - 1000. Default
                is 1000.
            starting_after: A token used by the server to indicate the start of the page. Often this
                is a timestamp or an ID but it is not limited to those. This parameter
                should not be defined by client applications. The link for the first,
                last, prev, or next page in the HTTP Link header should define it.
            ending_before: A token used by the server to indicate the end of the page. Often this is
                a timestamp or an ID but it is not limited to those. This parameter
                should not be defined by client applications. The link for the first,
                last, prev, or next page in the HTTP Link header should define it.
            subscription_ids: List of subscription ids to fetch.
            organization_ids: Organizations to get associated subscriptions for.
            statuses: List of statuses that returned subscriptions can have.
            product_types: List of product types that returned subscriptions need to have
                entitlements for.
            skus: List of SKUs that returned subscriptions need to have entitlements for.
            name: Search for subscription name.
            start_date: Filter subscriptions by start date, ISO 8601 format. To filter with a range
                of dates, use 'startDate[<option>]=?' in the request. Accepted options
                include lt, gt, lte, gte.
            end_date: Filter subscriptions by end date, ISO 8601 format. To filter with a range of
                dates, use 'endDate[<option>]=?' in the request. Accepted options
                include lt, gt, lte, gte.
            total_pages: use with per_page to get total results up to total_pages * per_page; -1 or
                "all" for all pages.
            direction: direction to paginate, either "next" (default) or "prev" page.

        Returns:
            Successful operation.

        Note:
            Returns a lazy PaginatedResponse
            that can be iterated or collected with `.collect()`.
            Page metadata is available on `.meta` and `.meta_pages`.

        Example API response:
            ```json
            [
              {
                "subscriptionId": "2345",
                "name": "Corporate subscription",
                "description": "A description",
                "status": "active",
                "startDate": "2027-06-30T00:00:00Z",
                "endDate": "2028-06-30T00:00:00Z",
                "lastUpdatedAt": "2027-09-21T00:00:00Z",
                "webOrderId": "55598764",
                "type": "termed",
                "smartAccount": {
                  "status": "active",
                  "account": {
                    "id": "99995678",
                    "name": "Corporate Smart Account",
                    "domain": "smart_account_domain"
                  }
                },
                "renewalRequested": false,
                "productTypes": [
                  "wireless"
                ],
                "entitlements": [
                  {
                    "sku": "LIC-MS-400-L-A",
                    "seats": {
                      "assigned": 10,
                      "available": 15,
                      "limit": 25
                    }
                  }
                ],
                "counts": {
                  "seats": {
                    "assigned": 10,
                    "available": 15,
                    "limit": 25
                  },
                  "networks": 1,
                  "organizations": 1
                },
                "enterpriseAgreement": {
                  "suites": [
                    "networking"
                  ]
                }
              }
            ]
            ```

        """
        path = f"/administered/licensing/subscription/subscriptions"

        params: dict[str, Any] = {}
        if per_page is not None:
            params["perPage"] = per_page
        if starting_after is not None:
            params["startingAfter"] = starting_after
        if ending_before is not None:
            params["endingBefore"] = ending_before
        if subscription_ids is not None:
            params["subscriptionIds[]"] = subscription_ids
        if organization_ids is not None:
            params["organizationIds[]"] = organization_ids
        if statuses is not None:
            params["statuses[]"] = statuses
        if product_types is not None:
            params["productTypes[]"] = product_types
        if skus is not None:
            params["skus[]"] = skus
        if name is not None:
            params["name"] = name
        if start_date is not None:
            params["startDate"] = start_date
        if end_date is not None:
            params["endDate"] = end_date

        return self._session.get_pages(
            scope="licensing",
            operation_id="getAdministeredLicensingSubscriptionSubscriptions",
            path=path,
            params=params,
            total_pages=total_pages,
            direction=direction,
            item_schema=GetAdministeredLicensingSubscriptionSubscriptionsResponseItem,
        )

    def claim_administered_licensing_subscription_subscriptions(
        self,
        *,
        claim_key: str,
        organization_id: str,
        validate: bool | None = None,
        name: str | None = None,
        description: str | None = None,
    ) -> ClaimAdministeredLicensingSubscriptionSubscriptionsResponse:
        """Claim a subscription into an organization.

        [API documentation: claimAdministeredLicensingSubscriptionSubscriptions](https://developer.cisco.com/meraki/api-v1/#!claim-administered-licensing-subscription-subscriptions)

        Args:
            validate: Check if the provided claim key is valid and can be claimed into the
                organization.
            claim_key: The subscription's claim key.
            organization_id: The id of the organization claiming the subscription.
            name: Friendly name to identify the subscription.
            description: Extra details or notes about the subscription.

        Returns:
            Successful operation.

        Example API response:
            ```json
            {
              "subscriptionId": "2345",
              "name": "Corporate subscription",
              "description": "A description",
              "status": "active",
              "startDate": "2027-06-30T00:00:00Z",
              "endDate": "2028-06-30T00:00:00Z",
              "lastUpdatedAt": "2027-09-21T00:00:00Z",
              "webOrderId": "55598764",
              "type": "termed",
              "smartAccount": {
                "status": "active",
                "account": {
                  "id": "99995678",
                  "name": "Corporate Smart Account",
                  "domain": "smart_account_domain"
                }
              },
              "renewalRequested": false,
              "productTypes": [
                "wireless"
              ],
              "entitlements": [
                {
                  "sku": "LIC-MS-400-L-A",
                  "seats": {
                    "assigned": 10,
                    "available": 15,
                    "limit": 25
                  }
                }
              ],
              "counts": {
                "seats": {
                  "assigned": 10,
                  "available": 15,
                  "limit": 25
                },
                "networks": 1,
                "organizations": 1
              },
              "enterpriseAgreement": {
                "suites": [
                  "networking"
                ]
              }
            }
            ```

        """
        path = f"/administered/licensing/subscription/subscriptions/claim"

        params: dict[str, Any] = {}
        if validate is not None:
            params["validate"] = validate

        payload: dict[str, Any] = {}
        if claim_key is not None:
            payload["claimKey"] = claim_key
        if organization_id is not None:
            payload["organizationId"] = organization_id
        if name is not None:
            payload["name"] = name
        if description is not None:
            payload["description"] = description

        return self._session.post(
            scope="licensing",
            operation_id="claimAdministeredLicensingSubscriptionSubscriptions",
            path=path,
            json=payload,
            response_schema=ClaimAdministeredLicensingSubscriptionSubscriptionsResponse,
        )

    def validate_administered_licensing_subscription_subscriptions_claim_key(
        self, claim_key: str
    ) -> ValidateAdministeredLicensingSubscriptionSubscriptionsClaimKeyResponse:
        """Find a subscription by claim key.

        [API documentation: validateAdministeredLicensingSubscriptionSubscriptionsClaimKey](https://developer.cisco.com/meraki/api-v1/#!validate-administered-licensing-subscription-subscriptions-claim-key)

        Args:
            claim_key: The subscription's claim key.

        Returns:
            Successful operation.

        Example API response:
            ```json
            {
              "subscriptionId": "2345",
              "name": "Corporate subscription",
              "description": "A description",
              "status": "active",
              "startDate": "2027-06-30T00:00:00Z",
              "endDate": "2028-06-30T00:00:00Z",
              "lastUpdatedAt": "2027-09-21T00:00:00Z",
              "webOrderId": "55598764",
              "type": "termed",
              "smartAccount": {
                "status": "active",
                "account": {
                  "id": "99995678",
                  "name": "Corporate Smart Account",
                  "domain": "smart_account_domain"
                }
              },
              "renewalRequested": false,
              "productTypes": [
                "wireless"
              ],
              "entitlements": [
                {
                  "sku": "LIC-MS-400-L-A",
                  "seats": {
                    "assigned": 10,
                    "available": 15,
                    "limit": 25
                  }
                }
              ],
              "counts": {
                "seats": {
                  "assigned": 10,
                  "available": 15,
                  "limit": 25
                },
                "networks": 1,
                "organizations": 1
              },
              "enterpriseAgreement": {
                "suites": [
                  "networking"
                ]
              }
            }
            ```

        """
        path = f"/administered/licensing/subscription/subscriptions/claimKey/validate"

        payload: dict[str, Any] = {}
        if claim_key is not None:
            payload["claimKey"] = claim_key

        return self._session.post(
            scope="licensing",
            operation_id="validateAdministeredLicensingSubscriptionSubscriptionsClaimKey",
            path=path,
            json=payload,
            response_schema=ValidateAdministeredLicensingSubscriptionSubscriptionsClaimKeyResponse,
        )

    def get_administered_licensing_subscription_subscriptions_compliance_statuses(
        self, organization_ids: list[str], *, subscription_ids: list[str] | None = None
    ) -> PaginatedResponse[
        GetAdministeredLicensingSubscriptionSubscriptionsComplianceStatusesResponseItem
    ]:
        """Get compliance status for requested subscriptions.

        [API documentation: getAdministeredLicensingSubscriptionSubscriptionsComplianceStatuses](https://developer.cisco.com/meraki/api-v1/#!get-administered-licensing-subscription-subscriptions-compliance-statuses)

        Args:
            organization_ids: Organizations to get subscription compliance information for.
            subscription_ids: Subscription ids.

        Returns:
            Successful operation.

        Note:
            Returns a lazy PaginatedResponse
            that can be iterated or collected with `.collect()`.
            Page metadata is available on `.meta` and `.meta_pages`.

        Example API response:
            ```json
            [
              {
                "subscription": {
                  "id": "12345",
                  "name": "Corporate Subscription",
                  "status": "active"
                },
                "violations": {
                  "byProductClass": [
                    {
                      "productClass": "MS 100 Small",
                      "gracePeriodEndsAt": "2023-12-07T00:00:00Z",
                      "missing": {
                        "entitlements": [
                          {
                            "sku": "LIC-MS-100-S-E",
                            "quantity": 11
                          }
                        ]
                      }
                    }
                  ]
                }
              }
            ]
            ```

        """
        path = f"/administered/licensing/subscription/subscriptions/compliance/statuses"

        params: dict[str, Any] = {}
        if organization_ids is not None:
            params["organizationIds[]"] = organization_ids
        if subscription_ids is not None:
            params["subscriptionIds[]"] = subscription_ids

        return self._session.get_pages(
            scope="licensing",
            operation_id="getAdministeredLicensingSubscriptionSubscriptionsComplianceStatuses",
            path=path,
            params=params,
            item_schema=GetAdministeredLicensingSubscriptionSubscriptionsComplianceStatusesResponseItem,
        )

    def bind_administered_licensing_subscription_subscription(
        self,
        subscription_id: str,
        *,
        validate: bool | None = None,
        network_ids: list[str] | None = None,
    ) -> BindAdministeredLicensingSubscriptionSubscriptionResponse:
        """Bind networks to a subscription.

        [API documentation: bindAdministeredLicensingSubscriptionSubscription](https://developer.cisco.com/meraki/api-v1/#!bind-administered-licensing-subscription-subscription)

        Args:
            subscription_id: Subscription ID.
            validate: Check if the provided networks can be bound to the subscription. Returns any
                licensing problems and does not commit the results.
            network_ids: List of network ids to bind to the subscription.

        Returns:
            Successful operation.

        Example API response:
            ```json
            {
              "subscriptionId": "XY1234567",
              "networks": [
                {
                  "id": "L_1234",
                  "name": "Corporate network"
                }
              ],
              "errors": [
                "Insufficient licenses"
              ],
              "insufficientEntitlements": [
                {
                  "sku": "LIC-MS-400-L-A",
                  "quantity": 5
                }
              ]
            }
            ```

        """
        subscription_id = urllib.parse.quote(str(subscription_id), safe="")
        path = f"/administered/licensing/subscription/subscriptions/{subscription_id}/bind"

        params: dict[str, Any] = {}
        if validate is not None:
            params["validate"] = validate

        payload: dict[str, Any] = {}
        if network_ids is not None:
            payload["networkIds"] = network_ids

        return self._session.post(
            scope="licensing",
            operation_id="bindAdministeredLicensingSubscriptionSubscription",
            path=path,
            json=payload,
            response_schema=BindAdministeredLicensingSubscriptionSubscriptionResponse,
        )

    def get_organization_licensing_coterm_licenses(
        self,
        organization_id: str,
        *,
        per_page: int | None = None,
        starting_after: str | None = None,
        ending_before: str | None = None,
        invalidated: bool | None = None,
        expired: bool | None = None,
        total_pages: int | Literal["all"] = "all",
        direction: Literal["prev", "next"] = "next",
    ) -> PaginatedResponse[GetOrganizationLicensingCotermLicensesResponseItem]:
        """List the licenses in a coterm organization.

        [API documentation: getOrganizationLicensingCotermLicenses](https://developer.cisco.com/meraki/api-v1/#!get-organization-licensing-coterm-licenses)

        Args:
            organization_id: Organization ID.
            per_page: The number of entries per page returned. Acceptable range is 3 - 1000. Default
                is 1000.
            starting_after: A token used by the server to indicate the start of the page. Often this
                is a timestamp or an ID but it is not limited to those. This parameter
                should not be defined by client applications. The link for the first,
                last, prev, or next page in the HTTP Link header should define it.
            ending_before: A token used by the server to indicate the end of the page. Often this is
                a timestamp or an ID but it is not limited to those. This parameter
                should not be defined by client applications. The link for the first,
                last, prev, or next page in the HTTP Link header should define it.
            invalidated: Filter for licenses that are invalidated.
            expired: Filter for licenses that are expired.
            total_pages: use with per_page to get total results up to total_pages * per_page; -1 or
                "all" for all pages.
            direction: direction to paginate, either "next" (default) or "prev" page.

        Returns:
            Successful operation.

        Note:
            Returns a lazy PaginatedResponse
            that can be iterated or collected with `.collect()`.
            Page metadata is available on `.meta` and `.meta_pages`.

        Example API response:
            ```json
            [
              {
                "key": "Z2AA-BBBB-CCCC",
                "organizationId": "123456",
                "duration": 365,
                "mode": "addDevices",
                "startedAt": "2022-05-02T10:52:00Z",
                "claimedAt": "2022-07-04T16:23:00Z",
                "invalidated": true,
                "invalidatedAt": "2022-07-04T16:23:00Z",
                "expired": false,
                "editions": [
                  {
                    "edition": "Enterprise",
                    "productType": "appliance"
                  }
                ],
                "counts": [
                  {
                    "model": "MR Enterprise",
                    "count": 2
                  }
                ]
              }
            ]
            ```

        """
        organization_id = urllib.parse.quote(str(organization_id), safe="")
        path = f"/organizations/{organization_id}/licensing/coterm/licenses"

        params: dict[str, Any] = {}
        if per_page is not None:
            params["perPage"] = per_page
        if starting_after is not None:
            params["startingAfter"] = starting_after
        if ending_before is not None:
            params["endingBefore"] = ending_before
        if invalidated is not None:
            params["invalidated"] = invalidated
        if expired is not None:
            params["expired"] = expired

        return self._session.get_pages(
            scope="licensing",
            operation_id="getOrganizationLicensingCotermLicenses",
            path=path,
            params=params,
            total_pages=total_pages,
            direction=direction,
            item_schema=GetOrganizationLicensingCotermLicensesResponseItem,
        )

    def move_organization_licensing_coterm_licenses(
        self,
        *,
        organization_id: str,
        destination: MoveOrganizationLicensingCotermLicensesDestination,
        licenses: list[MoveOrganizationLicensingCotermLicensesLicensesItem],
    ) -> MoveOrganizationLicensingCotermLicensesResponse:
        """Moves a license to a different organization (coterm only).

        [API documentation: moveOrganizationLicensingCotermLicenses](https://developer.cisco.com/meraki/api-v1/#!move-organization-licensing-coterm-licenses)

        Args:
            organization_id: Organization ID.
            destination: Destination data for the license move.
            licenses: The list of licenses to move.

        Returns:
            Successful operation.

        Example API response:
            ```json
            {
              "remainderLicenses": [
                {
                  "key": "Z2AA-BBBB-CCCC",
                  "organizationId": "123456",
                  "duration": 365,
                  "mode": "addDevices",
                  "startedAt": "2022-05-02T10:52:00Z",
                  "claimedAt": "2022-07-04T16:23:00Z",
                  "invalidated": true,
                  "invalidatedAt": "2022-07-04T16:23:00Z",
                  "expired": false,
                  "editions": [
                    {
                      "edition": "Enterprise",
                      "productType": "appliance"
                    }
                  ],
                  "counts": [
                    {
                      "model": "MR Enterprise",
                      "count": 2
                    }
                  ]
                }
              ],
              "movedLicenses": [
                {
                  "key": "Z2AA-BBBB-CCCC",
                  "organizationId": "123456",
                  "duration": 365,
                  "mode": "addDevices",
                  "startedAt": "2022-05-02T10:52:00Z",
                  "claimedAt": "2022-07-04T16:23:00Z",
                  "invalidated": true,
                  "invalidatedAt": "2022-07-04T16:23:00Z",
                  "expired": false,
                  "editions": [
                    {
                      "edition": "Enterprise",
                      "productType": "appliance"
                    }
                  ],
                  "counts": [
                    {
                      "model": "MR Enterprise",
                      "count": 2
                    }
                  ]
                }
              ]
            }
            ```

        """
        organization_id = urllib.parse.quote(str(organization_id), safe="")
        path = f"/organizations/{organization_id}/licensing/coterm/licenses/move"

        payload: dict[str, Any] = {}
        if destination is not None:
            payload["destination"] = destination.model_dump(by_alias=True, exclude_none=True)
        if licenses is not None:
            payload["licenses"] = [
                item.model_dump(by_alias=True, exclude_none=True) for item in licenses
            ]

        return self._session.post(
            scope="licensing",
            operation_id="moveOrganizationLicensingCotermLicenses",
            path=path,
            json=payload,
            response_schema=MoveOrganizationLicensingCotermLicensesResponse,
        )
