# [장내채권] 주문/계좌 - 장내채권 매도주문
# 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__)

##############################################################################################
# [장내채권] 주문/계좌 > 장내채권 매도주문 [국내주식-123]
##############################################################################################

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

def sell(
        cano: str,
        acnt_prdt_cd: str,
        ord_dvsn: str,
        pdno: str,
        ord_qty2: str,
        bond_ord_unpr: str,
        sprx_yn: str,
        samt_mket_ptci_yn: str,
        sll_agco_opps_sll_yn: str,
        bond_rtl_mket_yn: str,
        buy_dt: str = "",
        buy_seq: str = "",
        mgco_aptm_odno: str = "",
        ord_svr_dvsn_cd: str = "0",
        ctac_tlno: str = ""
) -> Optional[pd.DataFrame]:
    """
    [장내채권] 주문/계좌 
    장내채권 매도주문[국내주식-123]
    장내채권 매도주문 API를 호출하여 DataFrame으로 반환합니다.
    
    Args:
        cano (str): 종합계좌번호
        acnt_prdt_cd (str): 계좌상품코드
        ord_dvsn (str): 주문구분
        pdno (str): 상품번호
        ord_qty2 (str): 주문수량2
        bond_ord_unpr (str): 채권주문단가
        sprx_yn (str): 분리과세여부
        samt_mket_ptci_yn (str): 소액시장참여여부
        sll_agco_opps_sll_yn (str): 매도대행사반대매도여부
        bond_rtl_mket_yn (str): 채권소매시장여부
        buy_dt (str, optional): 매수일자. Defaults to "".
        buy_seq (str, optional): 매수순번. Defaults to "".
        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 = sell(
        ...     cano=trenv.my_acct,
        ...     acnt_prdt_cd=trenv.my_prod,
        ...     ord_dvsn="01",
        ...     pdno="KR6095572D81",
        ...     ord_qty2="1",
        ...     bond_ord_unpr="10000.0",
        ...     sprx_yn="N",
        ...     samt_mket_ptci_yn="N",
        ...     sll_agco_opps_sll_yn="N",
        ...     bond_rtl_mket_yn="N"
        ... )
        >>> print(df)
    """
    tr_id = "TTTC0958U"

    params = {
        "CANO": cano,
        "ACNT_PRDT_CD": acnt_prdt_cd,
        "ORD_DVSN": ord_dvsn,
        "PDNO": pdno,
        "ORD_QTY2": ord_qty2,
        "BOND_ORD_UNPR": bond_ord_unpr,
        "SPRX_YN": sprx_yn,
        "BUY_DT": buy_dt,
        "BUY_SEQ": buy_seq,
        "SAMT_MKET_PTCI_YN": samt_mket_ptci_yn,
        "SLL_AGCO_OPPS_SLL_YN": sll_agco_opps_sll_yn,
        "BOND_RTL_MKET_YN": bond_rtl_mket_yn,
        "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()
