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

from lseg_analytics.core.common._resource_base import ResourceBase
from lseg_analytics.core.exceptions import (
    LibraryException,
    ResourceNotFound,
    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,
    RequestPatternEnum,
    ResourceType,
    SortingOrderEnum,
    TenorBasisSwapOverride,
    VanillaIrsOverride,
)
from lseg_analytics.pricing._client.client import Client
from lseg_analytics.pricing.async_handler._async_response import (
    AsyncPollingResponse,
    AsyncRequestResponse,
    check_async_polling_response,
    check_async_request_response,
)

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
        Identifies the specific type of resource.
    id : str, optional
        Unique identifier for the IrSwap. Generated during resource creation and formatted as a UUID.
    location : Location
        Specifies the location of the IrSwap on the platform. Used for resource addressing and organization.
    description : Description, optional
        Contains descriptive information about the IrSwap such as summary and categorization tags. Used for documentation and search.
    definition : IrSwapDefinition
        Defines all core attributes of the IrSwap required by its type.

    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.solveResult : Get the response of the $solve async action once completed
    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.
    IrSwap.valueResult : Get the response of the $value async action once completed

    Examples
    --------


    """

    _definition_class = IrSwapDefinition

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

        Parameters
        ----------
        definition : IrSwapDefinition
            Defines all core attributes of the IrSwap required by its type.
        description : Description, optional
            Contains descriptive information about the IrSwap such as summary and categorization tags. Used for documentation and search.

        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 for the IrSwap. Generated during resource creation and formatted as a UUID.

        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
            Specifies the location of the IrSwap on the platform. Used for resource addressing and organization.

        Examples
        --------


        """
        return self._location

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

    def _create(self, location: Location) -> None:
        """
        Create and store a new IrSwap on the platform.

        Parameters
        ----------
        location : Location
            Specifies the location of the IrSwap on the platform. Used for resource addressing and organization.

        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 stored on the platform. The IrSwap can be identified either by its unique ID (UUID/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,
        request_pattern: Optional[Union[str, RequestPatternEnum]] = RequestPatternEnum.SYNC,
    ) -> Union[IrSwapInstrumentSolveResponseFieldsOnResourceResponseData, AsyncRequestResponse]:
        """
        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
            Configuration parameters that control the analytics computation.
        market_data : MarketData, optional
            Market data inputs used for the analytics computation.
            Can include rates, curves, surfaces, quotes, and other relevant market data.
        return_market_data : bool, optional
            Controls whether market data used in computations should be included in the response.
            Set to true to include market data details in the response.
            Defaults to false.
        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//'
        request_pattern : Union[str, RequestPatternEnum], optional
            Header indicating whether the request is synchronous or asynchronous polling.
            When asyncPolling is used, the operation should return a 202 Accepted response with a Location header to poll for the final result.

        Returns
        --------
        Union[IrSwapInstrumentSolveResponseFieldsOnResourceResponseData, AsyncRequestResponse]


        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.7046893212640555
            },
            "description": {
                "instrumentTag": "",
                "instrumentDescription": "Pay USD Annual 3.7% vs Receive USD Annual +0bp SOFR 2036-02-19",
                "startDate": "2026-02-18",
                "endDate": "2036-02-19",
                "tenor": "10Y"
            },
            "valuation": {
                "accrued": {
                    "value": 0.0,
                    "percent": 0.0,
                    "dealCurrency": {
                        "value": 0.0,
                        "currency": "USD"
                    },
                    "reportCurrency": {
                        "value": 0.0,
                        "currency": "USD"
                    }
                },
                "marketValue": {
                    "value": -9.31322574615479e-10,
                    "dealCurrency": {
                        "value": -9.31322574615479e-10,
                        "currency": "USD"
                    },
                    "reportCurrency": {
                        "value": -9.31322574615479e-10,
                        "currency": "USD"
                    }
                },
                "cleanMarketValue": {
                    "value": -9.31322574615479e-10,
                    "dealCurrency": {
                        "value": -9.31322574615479e-10,
                        "currency": "USD"
                    },
                    "reportCurrency": {
                        "value": -9.31322574615479e-10,
                        "currency": "USD"
                    }
                }
            },
            "risk": {
                "duration": {
                    "value": -8.50972758988991
                },
                "modifiedDuration": {
                    "value": -8.19702875855138
                },
                "benchmarkHedgeNotional": {
                    "value": -9926401.55504069,
                    "currency": "USD"
                },
                "annuity": {
                    "value": -8394.47615887458,
                    "dealCurrency": {
                        "value": -8394.47615887458,
                        "currency": "USD"
                    },
                    "reportCurrency": {
                        "value": -8394.47615887458,
                        "currency": "USD"
                    }
                },
                "dv01": {
                    "value": -8191.61698718183,
                    "bp": -8.19161698718183,
                    "dealCurrency": {
                        "value": -8191.61698718183,
                        "currency": "USD"
                    },
                    "reportCurrency": {
                        "value": -8191.61698718183,
                        "currency": "USD"
                    }
                },
                "pv01": {
                    "value": -8191.61698717717,
                    "bp": -8.19161698717717,
                    "dealCurrency": {
                        "value": -8191.61698717717,
                        "currency": "USD"
                    },
                    "reportCurrency": {
                        "value": -8191.61698717717,
                        "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.7%",
                    "interestType": "Fixed",
                    "currency": "USD",
                    "startDate": "2026-02-18",
                    "endDate": "2036-02-19",
                    "index": ""
                },
                "valuation": {
                    "accrued": {
                        "value": 0.0,
                        "percent": 0.0,
                        "dealCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        }
                    },
                    "marketValue": {
                        "value": 3109892.618338711,
                        "dealCurrency": {
                            "value": 3109892.618338711,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 3109892.618338711,
                            "currency": "USD"
                        }
                    },
                    "cleanMarketValue": {
                        "value": 3109892.618338711,
                        "dealCurrency": {
                            "value": 3109892.618338711,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 3109892.618338711,
                            "currency": "USD"
                        }
                    }
                },
                "risk": {
                    "duration": {
                        "value": 8.50972758988991
                    },
                    "modifiedDuration": {
                        "value": 8.214714976140979
                    },
                    "benchmarkHedgeNotional": {
                        "value": 0.0,
                        "currency": "USD"
                    },
                    "annuity": {
                        "value": 8394.476158874575,
                        "dealCurrency": {
                            "value": 8394.476158874575,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 8394.476158874575,
                            "currency": "USD"
                        }
                    },
                    "dv01": {
                        "value": 8209.29152812995,
                        "bp": 8.20929152812995,
                        "dealCurrency": {
                            "value": 8209.29152812995,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 8209.29152812995,
                            "currency": "USD"
                        }
                    },
                    "pv01": {
                        "value": 1564.9220031267032,
                        "bp": 1.5649220031267033,
                        "dealCurrency": {
                            "value": 1564.9220031267032,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 1564.9220031267032,
                            "currency": "USD"
                        }
                    },
                    "br01": {
                        "value": 0.0,
                        "dealCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        }
                    }
                },
                "cashflows": [
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.7046893212640555,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.9654899899332677,
                        "startDate": "2026-02-18",
                        "endDate": "2027-02-18",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.486855865377292,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2027-02-22"
                        },
                        "amount": {
                            "value": -375614.3339614945,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.7046893212640555,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.935558067831983,
                        "startDate": "2027-02-18",
                        "endDate": "2028-02-18",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.340166738650341,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2028-02-23"
                        },
                        "amount": {
                            "value": -375614.3339614945,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.7046893212640555,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.9053282881087193,
                        "startDate": "2028-02-18",
                        "endDate": "2029-02-20",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.345969095172574,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2029-02-21"
                        },
                        "amount": {
                            "value": -378701.57506254787,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.7046893212640555,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.8745318381700324,
                        "startDate": "2029-02-20",
                        "endDate": "2030-02-19",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.3919288007708603,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2030-02-20"
                        },
                        "amount": {
                            "value": -374585.25359447673,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.7046893212640555,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.8434332000905406,
                        "startDate": "2030-02-19",
                        "endDate": "2031-02-18",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.4506800905624857,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2031-02-20"
                        },
                        "amount": {
                            "value": -374585.25359447673,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.7046893212640555,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.8119278355950935,
                        "startDate": "2031-02-18",
                        "endDate": "2032-02-18",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.521934621541556,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2032-02-20"
                        },
                        "amount": {
                            "value": -375614.3339614945,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.7046893212640555,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.7801387372913783,
                        "startDate": "2032-02-18",
                        "endDate": "2033-02-18",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.5962339575009494,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2033-02-23"
                        },
                        "amount": {
                            "value": -376643.4143285123,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.7046893212640555,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.7490781399704934,
                        "startDate": "2033-02-18",
                        "endDate": "2034-02-21",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.665898617196661,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2034-02-22"
                        },
                        "amount": {
                            "value": -378701.57506254787,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.7046893212640555,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.7184725468300216,
                        "startDate": "2034-02-21",
                        "endDate": "2035-02-20",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.7326959360830747,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2035-02-21"
                        },
                        "amount": {
                            "value": -374585.25359447673,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.7046893212640555,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.6883505268226094,
                        "startDate": "2035-02-20",
                        "endDate": "2036-02-19",
                        "remainingNotional": 0.0,
                        "interestRateType": "FixedRate",
                        "zeroRate": {
                            "value": 3.797761977499059,
                            "unit": "Percentage"
                        },
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2036-02-20"
                        },
                        "amount": {
                            "value": -374585.25359447673,
                            "currency": "USD"
                        },
                        "payer": "Party1",
                        "receiver": "Party2",
                        "occurrence": "Future"
                    }
                ]
            },
            "secondLeg": {
                "description": {
                    "legTag": "ReceivedLeg",
                    "legDescription": "Receive USD Annual +0bp SOFR",
                    "interestType": "Float",
                    "currency": "USD",
                    "startDate": "2026-02-18",
                    "endDate": "2036-02-19",
                    "index": "SOFR"
                },
                "valuation": {
                    "accrued": {
                        "value": 0.0,
                        "percent": 0.0,
                        "dealCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        }
                    },
                    "marketValue": {
                        "value": 3109892.61833871,
                        "dealCurrency": {
                            "value": 3109892.61833871,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 3109892.61833871,
                            "currency": "USD"
                        }
                    },
                    "cleanMarketValue": {
                        "value": 3109892.61833871,
                        "dealCurrency": {
                            "value": 3109892.61833871,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 3109892.61833871,
                            "currency": "USD"
                        }
                    }
                },
                "risk": {
                    "duration": {
                        "value": 0.0
                    },
                    "modifiedDuration": {
                        "value": 0.01768621758959935
                    },
                    "benchmarkHedgeNotional": {
                        "value": 0.0,
                        "currency": "USD"
                    },
                    "annuity": {
                        "value": 0.0,
                        "dealCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        }
                    },
                    "dv01": {
                        "value": 17.67454094812274,
                        "bp": 0.01767454094812274,
                        "dealCurrency": {
                            "value": 17.67454094812274,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 17.67454094812274,
                            "currency": "USD"
                        }
                    },
                    "pv01": {
                        "value": -6626.694984050468,
                        "bp": -6.626694984050467,
                        "dealCurrency": {
                            "value": -6626.694984050468,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": -6626.694984050468,
                            "currency": "USD"
                        }
                    },
                    "br01": {
                        "value": 0.0,
                        "dealCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        }
                    }
                },
                "cashflows": [
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.4385000001265,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.9654899899332677,
                        "startDate": "2026-02-18",
                        "endDate": "2027-02-18",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.486855865377292,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2027-02-18",
                                "accrualStartDate": "2026-02-18",
                                "couponRate": {
                                    "value": 3.4385,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2026-02-18",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 3.4385,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2027-02-22"
                        },
                        "amount": {
                            "value": 348625.69445727015,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.1458929137358003,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.935558067831983,
                        "startDate": "2027-02-18",
                        "endDate": "2028-02-18",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.340166738650341,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2028-02-18",
                                "accrualStartDate": "2027-02-18",
                                "couponRate": {
                                    "value": 3.1458929,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2027-02-18",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 3.1458929,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2028-02-23"
                        },
                        "amount": {
                            "value": 318958.58708710194,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.3015030977682005,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.9053282881087193,
                        "startDate": "2028-02-18",
                        "endDate": "2029-02-20",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.345969095172574,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2029-02-20",
                                "accrualStartDate": "2028-02-18",
                                "couponRate": {
                                    "value": 3.3015032,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2028-02-18",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 3.3015032,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2029-02-21"
                        },
                        "amount": {
                            "value": 337486.98332741606,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.4823370510398,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.8745318381700324,
                        "startDate": "2029-02-20",
                        "endDate": "2030-02-19",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.3919288007708603,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2030-02-19",
                                "accrualStartDate": "2029-02-20",
                                "couponRate": {
                                    "value": 3.482337,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2029-02-20",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 3.482337,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2030-02-20"
                        },
                        "amount": {
                            "value": 352102.9684940242,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.6357262541897,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.8434332000905406,
                        "startDate": "2030-02-19",
                        "endDate": "2031-02-18",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.4506800905624857,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2031-02-18",
                                "accrualStartDate": "2030-02-19",
                                "couponRate": {
                                    "value": 3.6357262,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2030-02-19",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 3.6357262,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2031-02-20"
                        },
                        "amount": {
                            "value": 367612.32125695853,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.8261886420758,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.8119278355950935,
                        "startDate": "2031-02-18",
                        "endDate": "2032-02-18",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.521934621541556,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2032-02-18",
                                "accrualStartDate": "2031-02-18",
                                "couponRate": {
                                    "value": 3.8261886,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2031-02-18",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 3.8261886,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2032-02-20"
                        },
                        "amount": {
                            "value": 387933.01509935193,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 3.9735136507102005,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.7801387372913783,
                        "startDate": "2032-02-18",
                        "endDate": "2033-02-18",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.5962339575009494,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2033-02-18",
                                "accrualStartDate": "2032-02-18",
                                "couponRate": {
                                    "value": 3.9735136,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2032-02-18",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 3.9735136,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2033-02-23"
                        },
                        "amount": {
                            "value": 403973.8878222037,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 4.1008735422327005,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.7490781399704934,
                        "startDate": "2033-02-18",
                        "endDate": "2034-02-21",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.665898617196661,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2034-02-21",
                                "accrualStartDate": "2033-02-18",
                                "couponRate": {
                                    "value": 4.1008735,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2033-02-18",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 4.1008735,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2034-02-22"
                        },
                        "amount": {
                            "value": 419200.40653934266,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 4.2126924593093005,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.7184725468300216,
                        "startDate": "2034-02-21",
                        "endDate": "2035-02-20",
                        "remainingNotional": 10000000.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.7326959360830747,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2035-02-20",
                                "accrualStartDate": "2034-02-21",
                                "couponRate": {
                                    "value": 4.2126923,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2034-02-21",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 4.2126923,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2035-02-21"
                        },
                        "amount": {
                            "value": 425950.01533016254,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    },
                    {
                        "paymentType": "Interest",
                        "annualRate": {
                            "value": 4.3275784562810005,
                            "unit": "Percentage"
                        },
                        "discountFactor": 0.6883505268226094,
                        "startDate": "2035-02-20",
                        "endDate": "2036-02-19",
                        "remainingNotional": 0.0,
                        "interestRateType": "FloatingRate",
                        "zeroRate": {
                            "value": 3.797761977499059,
                            "unit": "Percentage"
                        },
                        "indexFixings": [
                            {
                                "accrualEndDate": "2036-02-19",
                                "accrualStartDate": "2035-02-20",
                                "couponRate": {
                                    "value": 4.3275785,
                                    "unit": "Percentage"
                                },
                                "fixingDate": "2035-02-20",
                                "forwardSource": "ZcCurve",
                                "referenceRate": {
                                    "value": 4.3275785,
                                    "unit": "Percentage"
                                },
                                "spreadBp": 0.0
                            }
                        ],
                        "date": {
                            "dateType": "AdjustableDate",
                            "date": "2036-02-20"
                        },
                        "amount": {
                            "value": 437566.2661350789,
                            "currency": "USD"
                        },
                        "payer": "Party2",
                        "receiver": "Party1",
                        "occurrence": "Projected"
                    }
                ]
            }
        }

        """

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

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

            output = response
            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 solve_result(self, *, operation_id: str) -> IrSwapInstrumentSolveResponseFieldsOnResourceResponseData:
        """
        Get the response of the $solve async action once completed

        Parameters
        ----------
        operation_id : str
            The operation identifier.

        Returns
        --------
        IrSwapInstrumentSolveResponseFieldsOnResourceResponseData


        Examples
        --------


        """

        try:
            logger.info("Calling solve_result for irSwap with id")

            response = Client().ir_swap_resource.solve_result(operation_id=operation_id)

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

            return output
        except Exception as err:
            logger.error("Error solve_result 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,
        request_pattern: Optional[Union[str, RequestPatternEnum]] = RequestPatternEnum.SYNC,
    ) -> Union[
        IrSwapInstrumentValuationResponseFieldsOnResourceResponseData,
        AsyncRequestResponse,
    ]:
        """
        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
            Configuration parameters that control the analytics computation.
        market_data : MarketData, optional
            Market data inputs used for the analytics computation.
            Can include rates, curves, surfaces, quotes, and other relevant market data.
        return_market_data : bool, optional
            Controls whether market data used in computations should be included in the response.
            Set to true to include market data details in the response.
            Defaults to false.
        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//'
        request_pattern : Union[str, RequestPatternEnum], optional
            Header indicating whether the request is synchronous or asynchronous polling.
            When asyncPolling is used, the operation should return a 202 Accepted response with a Location header to poll for the final result.

        Returns
        --------
        Union[IrSwapInstrumentValuationResponseFieldsOnResourceResponseData, AsyncRequestResponse]


        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": 3109807.92670901,
                "dealCurrency": {
                    "value": 3109807.92670901,
                    "currency": "USD"
                },
                "reportCurrency": {
                    "value": 3109807.92670901,
                    "currency": "USD"
                }
            },
            "cleanMarketValue": {
                "value": 3109807.92670901,
                "dealCurrency": {
                    "value": 3109807.92670901,
                    "currency": "USD"
                },
                "reportCurrency": {
                    "value": 3109807.92670901,
                    "currency": "USD"
                }
            }
        }

        """

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

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

            output = response
            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 value_result(self, *, operation_id: str) -> IrSwapInstrumentValuationResponseFieldsOnResourceResponseData:
        """
        Get the response of the $value async action once completed

        Parameters
        ----------
        operation_id : str
            The operation identifier.

        Returns
        --------
        IrSwapInstrumentValuationResponseFieldsOnResourceResponseData


        Examples
        --------


        """

        try:
            logger.info("Calling value_result for irSwap with id")

            response = Client().ir_swap_resource.value_result(operation_id=operation_id)

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

            return output
        except Exception as err:
            logger.error("Error value_result for irSwap with id.")
            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)

    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)
