from lseg_analytics.pricing.yield_book_rest import (
    bulk_compact_request,
    bulk_composite_request,
    BulkJsonInputItem,
    get_result,
    get_csv_bulk_result
)

import json as js

import pandas as pd
from io import StringIO

import time

# bulk_compact_request
compact_response = bulk_compact_request(
                    path="/bond/py",
                    name_expr='concat($.CUSIP,"_PY")',
                    body=
                        {
                            "globalSettings": 
                                { 
                                    "pricingDate": "2023-03-31" 
                                }, 
                            "input": 
                                [ 
                                    { 
                                        "identifier.$": "$.id", 
                                        "idType": "cusip", 
                                        "level.$": "$.level", 
                                        "curve": 
                                            {
                                                "curveType": "SWAP"
                                            }, 
                                        "volatility": 
                                            {
                                                "type": "Default"
                                            }
                                    }
                                ]
                        },
                    requests=
                        [
                            {
                                "id": "31418DY55", 
                                "level": "96.578"
                            }, 
                            {   
                                "id": "31418D4J8", 
                                "level": "96.131"
                            }
                        ],
                    params={},
                    create_job=True,
                    job="J-123456",
                    name="BulkCompactRun",
                    pri=0
                )

print("Created following requests:")

# Iterate through all request ID's
for result in compact_response.results:
    print(result.id)

# Due to async nature, code Will perform the fetch 10 times, as result is not always ready instantly, with 10 second lapse between attempts
attempt = 1

while attempt < 10:

    from lseg_analytics.core.exceptions import ResourceNotFound
    try:
        # Request bond indic with async post
        singluar_compact_result = get_result(request_id_parameter=compact_response.results[0].id)
        break
    except Exception as err:
        print(f"Attempt " + str(attempt) + " resulted in error retrieving results from:" + compact_response.results[0].id)
        if (isinstance(err, ResourceNotFound)
                and f"The result is not ready yet for requestID:{compact_response.results[0].id}" in str(err)):
            
            # Timer to allow for execution time
            time.sleep(10)
            attempt += 1
        else:
            raise err

# Print Compact singular result
print(js.dumps(singluar_compact_result, indent=4))

# Due to async nature, code Will perform the fetch 10 times, as result is not always ready instantly, with 10 second lapse between attempts
attempt = 1

while attempt < 10:

    from lseg_analytics.core.exceptions import ResourceNotFound
    try:
        # Request bond indic with async post
        bulk_compact_result_csv = get_csv_bulk_result(
                                                ids=[result.id for result in compact_response.results], 
                                                fields=["CUSIP:py.cusip", "Yield:py.yield", "OAS:py.oas"]
                                            )
        break
    except Exception as err:
        print(f"Attempt " + str(attempt) + " resulted in error retrieving results from:" + compact_response.results[0].id)
        if (isinstance(err, ResourceNotFound)
                and f"The result is not ready yet for requestID:{compact_response.results[0].id}" in str(err)):
            
            # Timer to allow for execution time
            time.sleep(10)
            attempt += 1
        else:
            raise err

# Print Bulk singular result
df = pd.read_csv(StringIO(bulk_compact_result_csv))
print(df)

# bulk_composite_request
composite_response = bulk_composite_request(
                        requests=[
                            BulkJsonInputItem(
                                path="/bond/py",
                                body=
                                    {
                                        "globalSettings": 
                                            { 
                                                "pricingDate": "2023-03-31"
                                            },
                                        "input": 
                                            [ 
                                                {
                                                    "identifier": "31418DY55",
                                                    "idType": "cusip", 
                                                    "level": "109.706", 
                                                    "curve": 
                                                        {
                                                            "curveType": "SWAP"
                                                        }, 
                                                    "volatility": 
                                                        {
                                                            "type": "Default" 
                                                        }
                                                },                                                
                                                {
                                                    "identifier": "31418D4J8",
                                                    "idType": "cusip", 
                                                    "level": "96.131", 
                                                    "curve": 
                                                        {
                                                            "curveType": "SWAP"
                                                        }, 
                                                    "volatility": 
                                                        {
                                                            "type": "Default" 
                                                        }
                                                }
                                            ]
                                    },
                            )
                        ],
                        create_job=True
                    )

print("Created following requests:")

# Iterate through all request ID's
for result in composite_response.results:
    print(result.id)

# Due to async nature, code Will perform the fetch 10 times, as result is not always ready instantly, with 10 second lapse between attempts
attempt = 1

while attempt < 10:

    from lseg_analytics.core.exceptions import ResourceNotFound
    try:
        # Request bond indic with async post
        bulk_composite_result = get_result(request_id_parameter=composite_response.results[0].id)
        break
    except Exception as err:
        print(f"Attempt " + str(attempt) + " resulted in error retrieving results from:" + composite_response.results[0].id)
        if (isinstance(err, ResourceNotFound)
                and f"The result is not ready yet for requestID:{composite_response.results[0].id}" in str(err)):
            
            # Timer to allow for execution time
            time.sleep(10)
            attempt += 1
        else:
            raise err

# Print Compact singular result
print(js.dumps(bulk_composite_result, indent=4))

# Due to async nature, code Will perform the fetch 10 times, as result is not always ready instantly, with 10 second lapse between attempts
attempt = 1

while attempt < 10:

    from lseg_analytics.core.exceptions import ResourceNotFound
    try:
        # Request bond indic with async post
        bulk_composite_result_csv = get_csv_bulk_result(
                                                    ids=[result.id for result in composite_response.results], 
                                                    fields=["CUSIP:py.cusip", "Yield:py.yield", "OAS:py.oas"]
                                                )
        break
    except Exception as err:
        print(f"Attempt " + str(attempt) + " resulted in error retrieving results from:" + composite_response.results[0].id)
        if (isinstance(err, ResourceNotFound)
                and f"The result is not ready yet for requestID:{composite_response.results[0].id}" in str(err)):
            
            # Timer to allow for execution time
            time.sleep(10)
            attempt += 1
        else:
            raise err

# Print Bulk singular result
df = pd.read_csv(StringIO(bulk_composite_result_csv))
print(df)