import copy
import datetime
from typing import Any, Dict, Iterator, List, Literal, Optional, Union

from lseg_analytics.core.common._resource_base import (
    AsyncPollingResponse,
    AsyncRequestResponse,
    ResourceBase,
)
from lseg_analytics.core.exceptions import (
    LibraryException,
    ResourceNotFound,
    check_async_polling_response,
    check_async_request_response,
    check_exception_and_raise,
    check_id,
)

from lseg_analytics.pricing._basic_client.models import (
    CrossCurencySwapOverride,
    CurencyBasisSwapOverride,
    Description,
    IrPricingParameters,
    IrSwapAsCollectionItem,
    IrSwapDefinition,
    IrSwapDefinitionInstrument,
    IrSwapInstrumentSolveResponseFieldsOnResourceResponseData,
    IrSwapInstrumentSolveResponseFieldsResponseData,
    IrSwapInstrumentValuationResponseFieldsOnResourceResponseData,
    IrSwapInstrumentValuationResponseFieldsResponseData,
    Location,
    MarketData,
    ResourceType,
    SortingOrderEnum,
    TenorBasisSwapOverride,
    VanillaIrsOverride,
)
from lseg_analytics.pricing._client.client import Client

from ._logger import logger


class IrSwap(ResourceBase):
    """
    IrSwap object.

    Contains all the necessary information to identify and define a IrSwap instance.

    Attributes
    ----------
    type : Union[str, ResourceType], optional
        Property defining the type of the resource.
    id : str, optional
        Unique identifier of the IrSwap.
    location : Location
        Object defining the location of the IrSwap in the platform.
    description : Description, optional
        Object defining metadata for the IrSwap.
    definition : IrSwapDefinition
        Object defining the IrSwap.

    See Also
    --------
    IrSwap.solve : Calculate analytics for an interest rate swap stored on the platform, by solving a variable parameter (e.g., fixed rate) provided in the request,
        so that a specified property (e.g., market value, duration) matches a target value.
        Provide an instrument ID in the request to perform the solving.
    IrSwap.value : Calculate analytics for an interest rate swap stored on the platform, including valuation results, risk metrics, and other relevant measures.
        Provide an instrument ID in the request to perform the valuation.

    Examples
    --------


    """

    _definition_class = IrSwapDefinition

    def __init__(self, definition: IrSwapDefinition, description: Optional[Description] = None):
        """
        IrSwap constructor

        Parameters
        ----------
        definition : IrSwapDefinition
            Object defining the IrSwap.
        description : Description, optional
            Object defining metadata for the IrSwap.

        Examples
        --------


        """
        self.definition: IrSwapDefinition = definition
        self.type: Optional[Union[str, ResourceType]] = "IrSwap"
        if description is None:
            self.description: Optional[Description] = Description(tags=[])
        else:
            self.description: Optional[Description] = description
        self._location: Location = Location(name="")
        self._id: Optional[str] = None

    @property
    def id(self):
        """
        Returns the IrSwap id

        Parameters
        ----------


        Returns
        --------
        str
            Unique identifier of the IrSwap.

        Examples
        --------


        """
        return self._id

    @id.setter
    def id(self, value):
        raise AttributeError("id is read only")

    @property
    def location(self):
        """
        Returns the IrSwap location

        Parameters
        ----------


        Returns
        --------
        Location
            Object defining the location of the IrSwap in the platform.

        Examples
        --------


        """
        return self._location

    @location.setter
    def location(self, value):
        raise AttributeError("location is read only")

    def _create(self, location: Location) -> None:
        """
        Save a new IrSwap in the platform

        Parameters
        ----------
        location : Location
            Object defining the location of the IrSwap in the platform.

        Returns
        --------
        None


        Examples
        --------


        """

        try:
            logger.info("Creating IrSwap")

            response = Client().ir_swaps_resource.create(
                location=location,
                description=self.description,
                definition=self.definition,
            )

            self._id = response.data.id

            self._location = response.data.location
            logger.info(f"IrSwap created with id: {self._id}")
        except Exception as err:
            logger.error("Error creating IrSwap:")
            raise err

    def _overwrite(self) -> None:
        """
        Overwrite a IrSwap that exists in the platform. The IrSwap can be identified either by its unique ID (GUID format) or by its location path (space/name).

        Parameters
        ----------


        Returns
        --------
        None


        Examples
        --------


        """
        logger.info(f"Overwriting IrSwap with id: {self._id}")
        Client().ir_swap_resource.overwrite(
            instrument_id=self._id,
            location=self._location,
            description=self.description,
            definition=self.definition,
        )

    def solve(
        self,
        *,
        pricing_preferences: Optional[IrPricingParameters] = None,
        market_data: Optional[MarketData] = None,
        return_market_data: Optional[bool] = None,
        fields: Optional[str] = None,
    ) -> IrSwapInstrumentSolveResponseFieldsOnResourceResponseData:
        """
        Calculate analytics for an interest rate swap stored on the platform, by solving a variable parameter (e.g., fixed rate) provided in the request,
        so that a specified property (e.g., market value, duration) matches a target value.
        Provide an instrument ID in the request to perform the solving.

        Parameters
        ----------
        pricing_preferences : IrPricingParameters, optional
            The parameters that control the computation of the analytics.
        market_data : MarketData, optional
            The market data used to compute the analytics.
        return_market_data : bool, optional
            Boolean property to determine if undelying market data used for calculation should be returned in the response
        fields : str, optional
            A parameter used to select the fields to return in response. If not provided, all fields will be returned.
            Some usage examples:
            1. Simply enumerating the fields, separating them by ',', e.g. 'fields=//please insert the selected fields here, e.g., field1, field2 //'
            2. Using parentheses to indicate nesting, e.g. 'fields= //please insert the selected field and subfields here, e.g., field1(subfield1, subfield2), field2(subfield3)//’
            3. Using forward slash '/' to indicate nesting, e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1/subfield1, field1/subfield2, field2/subfield3//’ (same result as example above)
            4. Operators can even be combined (forward slashes in brackets, not the way around), e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1(subfield1/subsubfield1), field2/subfield2//'

        Returns
        --------
        IrSwapInstrumentSolveResponseFieldsOnResourceResponseData


        Examples
        --------
        >>> # build the swap from 'LSEG/OIS_SOFR' template
        >>> fwd_start_sofr = create_from_vanilla_irs_template(template_reference = "LSEG/OIS_SOFR")
        >>>
        >>> # Swap needs to be saved in order for the solve class method to be executable
        >>> fwd_start_sofr.save(name="sofr_fwd_start_swap_exm")
        >>>
        >>> # set a solving variable between first and second leg and Fixed Rate or Spread
        >>> solving_variable = IrSwapSolvingVariable(leg='FirstLeg', name='FixedRate')
        >>>
        >>> # Apply solving target(s)
        >>> solving_target=IrSwapSolvingTarget(market_value=IrMeasure(value=0.0))
        >>>
        >>> # Setup the solving parameter object
        >>> solving_parameters = IrSwapSolvingParameters(variable=solving_variable, target=solving_target)
        >>>
        >>> # instantiate pricing parameters
        >>> pricing_parameters = IrPricingParameters(solving_parameters=solving_parameters)
        >>>
        >>> # solve the swap par rate
        >>> solving_response_object = fwd_start_sofr.solve(pricing_preferences=pricing_parameters)
        >>>
        >>> delete(name="sofr_fwd_start_swap_exm")
        >>>
        >>> print(js.dumps(solving_response_object.analytics.as_dict(), indent=4))
        {
            "solving": {
                "result": 3.5463439469617697
            },
            "description": {
                "instrumentTag": "",
                "instrumentDescription": "Pay USD Annual 3.55% vs Receive USD Annual +0bp SOFR 2035-10-29",
                "startDate": "2025-10-27",
                "endDate": "2035-10-29",
                "tenor": "10Y"
            },
            "valuation": {
                "accrued": {
                    "value": 0.0,
                    "percent": 0.0,
                    "dealCurrency": {
                        "value": 0.0,
                        "currency": "USD"
                    },
                    "reportCurrency": {
                        "value": 0.0,
                        "currency": "USD"
                    }
                },
                "marketValue": {
                    "value": 0.0,
                    "dealCurrency": {
                        "value": 0.0,
                        "currency": "USD"
                    },
                    "reportCurrency": {
                        "value": 0.0,
                        "currency": "USD"
                    }
                },
                "cleanMarketValue": {
                    "value": 0.0,
                    "dealCurrency": {
                        "value": 0.0,
                        "currency": "USD"
                    },
                    "reportCurrency": {
                        "value": 0.0,
                        "currency": "USD"
                    }
                }
            },
            "risk": {
                "duration": {
                    "value": -8.56947656958857
                },
                "modifiedDuration": {
                    "value": -8.26758226988537
                },
                "benchmarkHedgeNotional": {
                    "value": -9867032.90281232,
                    "currency": "USD"
                },
                "annuity": {
                    "value": -8458.68888950441,
                    "dealCurrency": {
                        "value": -8458.68888950441,
                        "currency": "USD"
                    },
                    "reportCurrency": {
                        "value": -8458.68888950441,
                        "currency": "USD"
                    }
                },
                "dv01": {
                    "value": -8262.48448179476,
                    "bp": -8.26248448179476,
                    "dealCurrency": {
                        "value": -8262.48448179476,
                        "currency": "USD"
                    },
                    "reportCurrency": {
                        "value": -8262.48448179476,
                        "currency": "USD"
                    }
                },
                "pv01": {
                    "value": -8262.48448179569,
                    "bp": -8.26248448179569,
                    "dealCurrency": {
                        "value": -8262.48448179569,
                        "currency": "USD"
                    },
                    "reportCurrency": {
                        "value": -8262.48448179569,
                        "currency": "USD"
                    }
                },
                "br01": {
                    "value": 0.0,
                    "dealCurrency": {
                        "value": 0.0,
                        "currency": "USD"
                    },
                    "reportCurrency": {
                        "value": 0.0,
                        "currency": "USD"
                    }
                }
            },
            "firstLeg": {
                "description": {
                    "legTag": "PaidLeg",
                    "legDescription": "Pay USD Annual 3.55%",
                    "interestType": "Fixed",
                    "currency": "USD",
                    "startDate": "2025-10-27",
                    "endDate": "2035-10-29",
                    "index": ""
                },
                "valuation": {
                    "accrued": {
                        "value": 0.0,
                        "percent": 0.0,
                        "dealCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        }
                    },
                    "marketValue": {
                        "value": 2999742.0142529323,
                        "dealCurrency": {
                            "value": 2999742.0142529323,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 2999742.0142529323,
                            "currency": "USD"
                        }
                    },
                    "cleanMarketValue": {
                        "value": 2999742.0142529323,
                        "dealCurrency": {
                            "value": 2999742.0142529323,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 2999742.0142529323,
                            "currency": "USD"
                        }
                    }
                },
                "risk": {
                    "duration": {
                        "value": 8.56947656958857
                    },
                    "modifiedDuration": {
                        "value": 8.28239644625482
                    },
                    "benchmarkHedgeNotional": {
                        "value": 0.0,
                        "currency": "USD"
                    },
                    "annuity": {
                        "value": 8458.68888950441,
                        "dealCurrency": {
                            "value": 8458.68888950441,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 8458.68888950441,
                            "currency": "USD"
                        }
                    },
                    "dv01": {
                        "value": 8277.289523748681,
                        "bp": 8.277289523748681,
                        "dealCurrency": {
                            "value": 8277.289523748681,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 8277.289523748681,
                            "currency": "USD"
                        }
                    },
                    "pv01": {
                        "value": 1515.427373928018,
                        "bp": 1.515427373928018,
                        "dealCurrency": {
                            "value": 1515.427373928018,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 1515.427373928018,
                            "currency": "USD"
                        }
                    },
                    "br01": {
                        "value": 0.0,
                        "dealCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        }
                    }
                },
                "cashflows": [
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.5463439469617697,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.9653674283396082,
                        "startDate": "2025-10-27",
                        "endDate": "2026-10-27",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.5284710162892807,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2026-10-29"
                        },
                        "amount": {
                            "value": -359559.87240029057,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.5463439469617697,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.9369989085889235,
                        "startDate": "2026-10-27",
                        "endDate": "2027-10-27",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.2797703420404334,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2027-10-29"
                        },
                        "amount": {
                            "value": -359559.87240029057,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.5463439469617697,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.908086260609748,
                        "startDate": "2027-10-27",
                        "endDate": "2028-10-27",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.241997308572442,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2028-10-31"
                        },
                        "amount": {
                            "value": -360544.9679411132,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.5463439469617697,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.878901204884654,
                        "startDate": "2028-10-27",
                        "endDate": "2029-10-29",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.263801889626894,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2029-10-30"
                        },
                        "amount": {
                            "value": -361530.06348193594,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.5463439469617697,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.8493280486512742,
                        "startDate": "2029-10-29",
                        "endDate": "2030-10-28",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.309063381666233,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2030-10-29"
                        },
                        "amount": {
                            "value": -358574.77685946785,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.5463439469617697,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.8193211503178378,
                        "startDate": "2030-10-28",
                        "endDate": "2031-10-27",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.36770998296112,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2031-10-29"
                        },
                        "amount": {
                            "value": -358574.77685946785,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.5463439469617697,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.7890352511100474,
                        "startDate": "2031-10-27",
                        "endDate": "2032-10-27",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.4346555451595373,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2032-10-29"
                        },
                        "amount": {
                            "value": -360544.9679411132,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.5463439469617697,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.7587867904887003,
                        "startDate": "2032-10-27",
                        "endDate": "2033-10-27",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.500890663664924,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2033-10-31"
                        },
                        "amount": {
                            "value": -359559.87240029057,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.5463439469617697,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.7288559144973165,
                        "startDate": "2033-10-27",
                        "endDate": "2034-10-27",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.5678493082607288,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2034-10-31"
                        },
                        "amount": {
                            "value": -359559.87240029057,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.5463439469617697,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.6994091989541407,
                        "startDate": "2034-10-27",
                        "endDate": "2035-10-29",
                        "remainingNotional": 0.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.6327792767828937,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2035-10-30"
                        },
                        "amount": {
                            "value": -361530.06348193594,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    }
                ]
            },
            "secondLeg": {
                "description": {
                    "legTag": "ReceivedLeg",
                    "legDescription": "Receive USD Annual +0bp SOFR",
                    "interestType": "Float",
                    "currency": "USD",
                    "startDate": "2025-10-27",
                    "endDate": "2035-10-29",
                    "index": "SOFR"
                },
                "valuation": {
                    "accrued": {
                        "value": 0.0,
                        "percent": 0.0,
                        "dealCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        }
                    },
                    "marketValue": {
                        "value": 2999742.0142529323,
                        "dealCurrency": {
                            "value": 2999742.0142529323,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 2999742.0142529323,
                            "currency": "USD"
                        }
                    },
                    "cleanMarketValue": {
                        "value": 2999742.0142529323,
                        "dealCurrency": {
                            "value": 2999742.0142529323,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 2999742.0142529323,
                            "currency": "USD"
                        }
                    }
                },
                "risk": {
                    "duration": {
                        "value": 0.0
                    },
                    "modifiedDuration": {
                        "value": 0.014814176369449721
                    },
                    "benchmarkHedgeNotional": {
                        "value": 0.0,
                        "currency": "USD"
                    },
                    "annuity": {
                        "value": 0.0,
                        "dealCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        }
                    },
                    "dv01": {
                        "value": 14.805041953921318,
                        "bp": 0.014805041953921318,
                        "dealCurrency": {
                            "value": 14.805041953921318,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 14.805041953921318,
                            "currency": "USD"
                        }
                    },
                    "pv01": {
                        "value": -6747.057107867673,
                        "bp": -6.747057107867673,
                        "dealCurrency": {
                            "value": -6747.057107867673,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": -6747.057107867673,
                            "currency": "USD"
                        }
                    },
                    "br01": {
                        "value": 0.0,
                        "dealCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        }
                    }
                },
                "cashflows": [
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.4734999515953007,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.9653674283396082,
                        "startDate": "2025-10-27",
                        "endDate": "2026-10-27",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.5284710162892807,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2026-10-27",
                                "accrualStartDate": "2025-10-27",
                                "couponRate": {
                                    "value": 3.4735,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2025-10-27",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 3.4735,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2026-10-29"
                        },
                        "amount": {
                            "value": 352174.30064785684,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 2.9862337752249,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.9369989085889235,
                        "startDate": "2026-10-27",
                        "endDate": "2027-10-27",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.2797703420404334,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2027-10-27",
                                "accrualStartDate": "2026-10-27",
                                "couponRate": {
                                    "value": 2.9862337,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2026-10-27",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 2.9862337,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2027-10-29"
                        },
                        "amount": {
                            "value": 302770.9244325246,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.1130214234307,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.908086260609748,
                        "startDate": "2027-10-27",
                        "endDate": "2028-10-27",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.241997308572442,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2028-10-27",
                                "accrualStartDate": "2027-10-27",
                                "couponRate": {
                                    "value": 3.1130214,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2027-10-27",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 3.1130214,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2028-10-31"
                        },
                        "amount": {
                            "value": 316490.5113821211,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.2834470278214005,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.878901204884654,
                        "startDate": "2028-10-27",
                        "endDate": "2029-10-29",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.263801889626894,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2029-10-29",
                                "accrualStartDate": "2028-10-27",
                                "couponRate": {
                                    "value": 3.283447,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2028-10-27",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 3.283447,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2029-10-30"
                        },
                        "amount": {
                            "value": 334729.183114015,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.4432389713441003,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.8493280486512742,
                        "startDate": "2029-10-29",
                        "endDate": "2030-10-28",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.309063381666233,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2030-10-28",
                                "accrualStartDate": "2029-10-29",
                                "couponRate": {
                                    "value": 3.443239,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2029-10-29",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 3.443239,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2030-10-29"
                        },
                        "amount": {
                            "value": 348149.7182136812,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.6113565906769,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.8193211503178378,
                        "startDate": "2030-10-28",
                        "endDate": "2031-10-27",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.36770998296112,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2031-10-27",
                                "accrualStartDate": "2030-10-28",
                                "couponRate": {
                                    "value": 3.6113565,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2030-10-28",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 3.6113565,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2031-10-29"
                        },
                        "amount": {
                            "value": 365148.2775017755,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.7746223735167006,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.7890352511100474,
                        "startDate": "2031-10-27",
                        "endDate": "2032-10-27",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.4346555451595373,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2032-10-27",
                                "accrualStartDate": "2031-10-27",
                                "couponRate": {
                                    "value": 3.7746224,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2031-10-27",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 3.7746224,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2032-10-29"
                        },
                        "amount": {
                            "value": 383753.2746408645,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.9088288148094,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.7587867904887003,
                        "startDate": "2032-10-27",
                        "endDate": "2033-10-27",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.500890663664924,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2033-10-27",
                                "accrualStartDate": "2032-10-27",
                                "couponRate": {
                                    "value": 3.9088287,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2032-10-27",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 3.9088287,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2033-10-31"
                        },
                        "amount": {
                            "value": 396311.8103903975,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 4.0488945232745,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.7288559144973165,
                        "startDate": "2033-10-27",
                        "endDate": "2034-10-27",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.5678493082607288,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2034-10-27",
                                "accrualStartDate": "2033-10-27",
                                "couponRate": {
                                    "value": 4.0488944,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2033-10-27",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 4.0488944,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2034-10-31"
                        },
                        "amount": {
                            "value": 410512.916943109,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 4.1639176097682,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.6994091989541407,
                        "startDate": "2034-10-27",
                        "endDate": "2035-10-29",
                        "remainingNotional": 0.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.6327792767828937,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2035-10-29",
                                "accrualStartDate": "2034-10-27",
                                "couponRate": {
                                    "value": 4.1639175,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2034-10-27",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 4.1639175,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2035-10-30"
                        },
                        "amount": {
                            "value": 424488.2674402582,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    }
                ]
            }
        }

        """

        try:
            logger.info("Calling solve for irSwap with id")
            check_id(self._id)

            response = Client().ir_swap_resource.solve(
                instrument_id=self._id,
                fields=fields,
                pricing_preferences=pricing_preferences,
                market_data=market_data,
                return_market_data=return_market_data,
            )

            output = response.data
            logger.info("Called solve for irSwap with id")

            return output
        except Exception as err:
            logger.error("Error solve for irSwap with id.")
            check_exception_and_raise(err, logger)

    def value(
        self,
        *,
        pricing_preferences: Optional[IrPricingParameters] = None,
        market_data: Optional[MarketData] = None,
        return_market_data: Optional[bool] = None,
        fields: Optional[str] = None,
    ) -> IrSwapInstrumentValuationResponseFieldsOnResourceResponseData:
        """
        Calculate analytics for an interest rate swap stored on the platform, including valuation results, risk metrics, and other relevant measures.
        Provide an instrument ID in the request to perform the valuation.

        Parameters
        ----------
        pricing_preferences : IrPricingParameters, optional
            The parameters that control the computation of the analytics.
        market_data : MarketData, optional
            The market data used to compute the analytics.
        return_market_data : bool, optional
            Boolean property to determine if undelying market data used for calculation should be returned in the response
        fields : str, optional
            A parameter used to select the fields to return in response. If not provided, all fields will be returned.
            Some usage examples:
            1. Simply enumerating the fields, separating them by ',', e.g. 'fields=//please insert the selected fields here, e.g., field1, field2 //'
            2. Using parentheses to indicate nesting, e.g. 'fields= //please insert the selected field and subfields here, e.g., field1(subfield1, subfield2), field2(subfield3)//’
            3. Using forward slash '/' to indicate nesting, e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1/subfield1, field1/subfield2, field2/subfield3//’ (same result as example above)
            4. Operators can even be combined (forward slashes in brackets, not the way around), e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1(subfield1/subsubfield1), field2/subfield2//'

        Returns
        --------
        IrSwapInstrumentValuationResponseFieldsOnResourceResponseData


        Examples
        --------
        >>> # build the swap from 'LSEG/OIS_SOFR' template
        >>> fwd_start_sofr = create_from_vanilla_irs_template(template_reference = "LSEG/OIS_SOFR")
        >>>
        >>> # Swap needs to be saved in order for the value class method to be executable
        >>> fwd_start_sofr.save(name="sofr_fwd_start_swap_exm")
        >>>
        >>> # instantiate pricing parameters
        >>> pricing_parameters = IrPricingParameters()
        >>>
        >>> # solve the swap par rate
        >>> valuing_response_object = fwd_start_sofr.value(pricing_preferences=pricing_parameters)
        >>>
        >>> delete(name="sofr_fwd_start_swap_exm")
        >>>
        >>> print(js.dumps(valuation_response.analytics[0].valuation.as_dict(), indent=4))
        {
            "accrued": {
                "value": 0.0,
                "percent": 0.0,
                "dealCurrency": {
                    "value": 0.0,
                    "currency": "USD"
                },
                "reportCurrency": {
                    "value": 0.0,
                    "currency": "USD"
                }
            },
            "marketValue": {
                "value": 2999742.01425293,
                "dealCurrency": {
                    "value": 2999742.01425293,
                    "currency": "USD"
                },
                "reportCurrency": {
                    "value": 2999742.01425293,
                    "currency": "USD"
                }
            },
            "cleanMarketValue": {
                "value": 2999742.01425293,
                "dealCurrency": {
                    "value": 2999742.01425293,
                    "currency": "USD"
                },
                "reportCurrency": {
                    "value": 2999742.01425293,
                    "currency": "USD"
                }
            }
        }

        """

        try:
            logger.info("Calling value for irSwap with id")
            check_id(self._id)

            response = Client().ir_swap_resource.value(
                instrument_id=self._id,
                fields=fields,
                pricing_preferences=pricing_preferences,
                market_data=market_data,
                return_market_data=return_market_data,
            )

            output = response.data
            logger.info("Called value for irSwap with id")

            return output
        except Exception as err:
            logger.error("Error value for irSwap with id.")
            check_exception_and_raise(err, logger)

    def save(self, *, name: Optional[str] = None, space: Optional[str] = None) -> bool:
        """
        Save IrSwap instance in the platform store.

        Parameters
        ----------
        name : str, optional
            The IrSwap name. The name parameter must be specified when the object is first created. Thereafter it is optional. For first creation, name must follow the pattern '^[A-Za-z0-9_]{1,50}$'.
        space : str, optional
            The space where the IrSwap is stored. Space is like a namespace where resources are stored. By default there are two spaces:
            LSEG is reserved for LSEG maintained resources, HOME is reserved for user's default space. If space is not specified, HOME will be used.

        Returns
        --------
        bool, optional
            True, if saved successfully, otherwise None


        Examples
        --------
        >>> # build the swap from 'LSEG/OIS_SOFR' template
        >>> fwd_start_sofr = create_from_vanilla_irs_template(template_reference = "LSEG/OIS_SOFR")
        >>>
        >>> swap_id = "SOFR_OIS_1Y2Y"
        >>>
        >>> swap_space = "HOME"
        >>>
        >>> try:
        >>>     # If the instrument does not exist in HOME space, we can save it
        >>>     fwd_start_sofr.save(name=swap_id, space=swap_space)
        >>>     print(f"Instrument {swap_id} saved in {swap_space} space.")
        >>> except:
        >>>     # Check if the instrument already exists in HOME space
        >>>     fwd_start_sofr = load(name=swap_id, space=swap_space)
        >>>     print(f"Instrument {swap_id} already exists in {swap_space} space.")
        Instrument SOFR_OIS_1Y2Y saved in HOME space.

        """
        try:
            logger.info("Saving IrSwap")
            if self._id:
                if name and name != self._location.name or (space and space != self._location.space):
                    raise LibraryException("When saving an existing resource, you may not change the name or space")
                self._overwrite()
                logger.info("IrSwap saved")
            elif name:
                location = Location(name=name, space=space)
                self._create(location=location)
                logger.info(f"IrSwap saved to space: {self._location.space} name: {self._location.name}")
            else:
                raise LibraryException("When saving for the first time, name must be defined.")
            return True
        except Exception as err:
            logger.info("IrSwap save failed")
            check_exception_and_raise(err, logger)

    def clone(self) -> "IrSwap":
        """
        Return the same object, without id, name and space

        Parameters
        ----------


        Returns
        --------
        IrSwap
            The cloned IrSwap object


        Examples
        --------


        """
        definition = self._definition_class()
        definition._data = copy.deepcopy(self.definition._data)
        description = None
        if self.description:
            description = Description()
            description._data = copy.deepcopy(self.description._data)
        return self.__class__(definition=definition, description=description)
