# [장내채권] 주문/계좌 - 장내채권 정정취소주문
# Generated by KIS API Generator (Single API Mode)
# -*- coding: utf-8 -*-
"""
Created on 2025-06-20

"""

import logging
from typing import Optional
import sys

import pandas as pd

sys.path.extend(['../..', '.'])
import kis_auth as ka

# 로깅 설정
logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

##############################################################################################
# [장내채권] 주문/계좌 > 장내채권 정정취소주문 [국내주식-125]
##############################################################################################

# 상수 정의
API_URL = "/uapi/domestic-bond/v1/trading/order-rvsecncl"

def order_rvsecncl(
    cano: str,
    acnt_prdt_cd: str,
    pdno: str,
    orgn_odno: str,
    ord_qty2: str,
    bond_ord_unpr: str,
    qty_all_ord_yn: str,
    rvse_cncl_dvsn_cd: str,
    mgco_aptm_odno: str = "",
    ord_svr_dvsn_cd: str = "0",
    ctac_tlno: str = ""
) -> Optional[pd.DataFrame]:
    """
    [장내채권] 주문/계좌 
    장내채권 정정취소주문[국내주식-125]
    장내채권 정정취소주문 API를 호출하여 DataFrame으로 반환합니다.
    
    Args:
        cano (str): 종합계좌번호
        acnt_prdt_cd (str): 계좌상품코드
        pdno (str): 상품번호
        orgn_odno (str): 원주문번호
        ord_qty2 (str): 주문수량2
        bond_ord_unpr (str): 채권주문단가
        qty_all_ord_yn (str): 잔량전부주문여부
        rvse_cncl_dvsn_cd (str): 정정취소구분코드
        mgco_aptm_odno (str, optional): 운용사지정주문번호. Defaults to "".
        ord_svr_dvsn_cd (str, optional): 주문서버구분코드. Defaults to "0".
        ctac_tlno (str, optional): 연락전화번호. Defaults to "".
        
    Returns:
        Optional[pd.DataFrame]: 장내채권 정정취소주문 데이터
        
    Example:
        >>> df = order_rvsecncl(
        ...     cano=trenv.my_acct,
        ...     acnt_prdt_cd=trenv.my_prod,
        ...     pdno="KR6095572D81",
        ...     orgn_odno="0000015402",
        ...     ord_qty2="2",
        ...     bond_ord_unpr="10460",
        ...     qty_all_ord_yn="Y",
        ...     rvse_cncl_dvsn_cd="01"
        ... )
        >>> print(df)
    """
    tr_id = "TTTC0953U"

    params = {
        "CANO": cano,
        "ACNT_PRDT_CD": acnt_prdt_cd,
        "PDNO": pdno,
        "ORGN_ODNO": orgn_odno,
        "ORD_QTY2": ord_qty2,
        "BOND_ORD_UNPR": bond_ord_unpr,
        "QTY_ALL_ORD_YN": qty_all_ord_yn,
        "RVSE_CNCL_DVSN_CD": rvse_cncl_dvsn_cd,
        "MGCO_APTM_ODNO": mgco_aptm_odno,
        "ORD_SVR_DVSN_CD": ord_svr_dvsn_cd,
        "CTAC_TLNO": ctac_tlno
    }

    res = ka._url_fetch(api_url=API_URL,
                         ptr_id=tr_id,
                         tr_cont="",
                         params=params,
                         postFlag=True
                )

    if res.isOK():
        if hasattr(res.getBody(), 'output'):
            output_data = res.getBody().output
            if not isinstance(output_data, list):
                output_data = [output_data]
            dataframe = pd.DataFrame(output_data)
        else:
            dataframe = pd.DataFrame()
            
        logger.info("Data fetch complete.")
        return dataframe
    else:
        logger.error("API call failed: %s - %s", res.getErrorCode(), res.getErrorMessage())
        res.printError(API_URL)
        return pd.DataFrame()
