# DOMSTK_RANK - 국내주식 당사매매종목 상위
# Generated by KIS API Generator (Single API Mode)
import logging
import sys
import time
from typing import Optional

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__)

##############################################################################################
# [국내주식] 순위분석 > 국내주식 당사매매종목 상위[v1_국내주식-104]
##############################################################################################

# 상수 정의
API_URL = "/uapi/domestic-stock/v1/ranking/traded-by-company"

def traded_by_company(
        fid_trgt_exls_cls_code: str,  # 대상 제외 구분 코드
        fid_cond_mrkt_div_code: str,  # 조건 시장 분류 코드
        fid_cond_scr_div_code: str,  # 조건 화면 분류 코드
        fid_div_cls_code: str,  # 분류 구분 코드
        fid_rank_sort_cls_code: str,  # 순위 정렬 구분 코드
        fid_input_date_1: str,  # 입력 날짜1
        fid_input_date_2: str,  # 입력 날짜2
        fid_input_iscd: str,  # 입력 종목코드
        fid_trgt_cls_code: str,  # 대상 구분 코드
        fid_aply_rang_vol: str,  # 적용 범위 거래량
        fid_aply_rang_prc_2: str,  # 적용 범위 가격2
        fid_aply_rang_prc_1: str,  # 적용 범위 가격1
        tr_cont: str = "",  # 연속 거래 여부
        dataframe: Optional[pd.DataFrame] = None,  # 누적 데이터프레임
        depth: int = 0,  # 현재 재귀 깊이
        max_depth: int = 10  # 최대 재귀 깊이
) -> Optional[pd.DataFrame]:
    """
    [국내주식] 순위분석 
    국내주식 당사매매종목 상위[v1_국내주식-104]
    국내주식 당사매매종목 상위 API를 호출하여 DataFrame으로 반환합니다.
    
    Args:
        fid_trgt_exls_cls_code (str): 0: 전체
        fid_cond_mrkt_div_code (str): 시장구분코드 (J:KRX, NX:NXT)
        fid_cond_scr_div_code (str): Unique key(20186)
        fid_div_cls_code (str): 0:전체, 1:관리종목, 2:투자주의, 3:투자경고, 4:투자위험예고, 5:투자위험, 6:보통주, 7:우선주
        fid_rank_sort_cls_code (str): 0:매도상위,1:매수상위
        fid_input_date_1 (str): 기간~
        fid_input_date_2 (str): ~기간
        fid_input_iscd (str): 0000:전체, 0001:거래소, 1001:코스닥, 2001:코스피200, 4001: KRX100
        fid_trgt_cls_code (str): 0: 전체
        fid_aply_rang_vol (str): 0: 전체, 100: 100주 이상
        fid_aply_rang_prc_2 (str): ~ 가격
        fid_aply_rang_prc_1 (str): 가격 ~
        tr_cont (str): 연속 거래 여부
        dataframe (Optional[pd.DataFrame]): 누적 데이터프레임
        depth (int): 현재 재귀 깊이
        max_depth (int): 최대 재귀 깊이 (기본값: 10)
        
    Returns:
        Optional[pd.DataFrame]: 국내주식 당사매매종목 상위 데이터
        
    Example:
        >>> df = traded_by_company(
        ...     fid_trgt_exls_cls_code="0",
        ...     fid_cond_mrkt_div_code="J",
        ...     fid_cond_scr_div_code="20186",
        ...     fid_div_cls_code="0",
        ...     fid_rank_sort_cls_code="0",
        ...     fid_input_date_1="20240314",
        ...     fid_input_date_2="20240315",
        ...     fid_input_iscd="0000",
        ...     fid_trgt_cls_code="0",
        ...     fid_aply_rang_vol="0",
        ...     fid_aply_rang_prc_2="",
        ...     fid_aply_rang_prc_1=""
        ... )
        >>> print(df)
    """
    # 필수 파라미터 검증
    if not fid_trgt_exls_cls_code:
        logger.error("fid_trgt_exls_cls_code is required. (e.g. '0')")
        return None
    if fid_cond_mrkt_div_code != "J":
        logger.error("fid_cond_mrkt_div_code is required. (e.g. 'J')")
        return None
    if not fid_cond_scr_div_code:
        logger.error("fid_cond_scr_div_code is required. (e.g. '20186')")
        return None
    if fid_div_cls_code not in ["0", "1", "2", "3", "4", "5", "6", "7"]:
        logger.error("fid_div_cls_code is required. (e.g. '0', '1', '2', '3', '4', '5', '6', '7')")
        return None
    if fid_rank_sort_cls_code not in ["0", "1"]:
        logger.error("fid_rank_sort_cls_code is required. (e.g. '0', '1')")
        return None
    if not fid_input_date_1:
        logger.error("fid_input_date_1 is required.")
        return None
    if not fid_input_date_2:
        logger.error("fid_input_date_2 is required.")
        return None
    if fid_input_iscd not in ["0000", "0001", "1001", "2001", "4001"]:
        logger.error("fid_input_iscd is required. (e.g. '0000', '0001', '1001', '2001', '4001')")
        return None
    if not fid_trgt_cls_code:
        logger.error("fid_trgt_cls_code is required. (e.g. '0')")
        return None
    if fid_aply_rang_vol not in ["0", "100"]:
        logger.error("fid_aply_rang_vol is required. (e.g. '0', '100')")
        return None

    # 최대 재귀 깊이 체크
    if depth >= max_depth:
        logger.warning("Maximum recursion depth (%d) reached. Stopping further requests.", max_depth)
        return dataframe if dataframe is not None else pd.DataFrame()


    tr_id = "FHPST01860000"

    params = {
        "fid_trgt_exls_cls_code": fid_trgt_exls_cls_code,
        "fid_cond_mrkt_div_code": fid_cond_mrkt_div_code,
        "fid_cond_scr_div_code": fid_cond_scr_div_code,
        "fid_div_cls_code": fid_div_cls_code,
        "fid_rank_sort_cls_code": fid_rank_sort_cls_code,
        "fid_input_date_1": fid_input_date_1,
        "fid_input_date_2": fid_input_date_2,
        "fid_input_iscd": fid_input_iscd,
        "fid_trgt_cls_code": fid_trgt_cls_code,
        "fid_aply_rang_vol": fid_aply_rang_vol,
        "fid_aply_rang_prc_2": fid_aply_rang_prc_2,
        "fid_aply_rang_prc_1": fid_aply_rang_prc_1,
    }

    # API 호출
    res = ka._url_fetch(API_URL, tr_id, tr_cont, params)

    if res.isOK():
        # 응답 데이터 처리
        if hasattr(res.getBody(), 'output'):
            current_data = pd.DataFrame(res.getBody().output)
        else:
            current_data = pd.DataFrame()

        if dataframe is not None:
            dataframe = pd.concat([dataframe, current_data], ignore_index=True)
        else:
            dataframe = current_data

        tr_cont = res.getHeader().tr_cont

        if tr_cont == "M":
            logger.info("Calling next page...")
            ka.smart_sleep()
            return traded_by_company(
                fid_trgt_exls_cls_code,
                fid_cond_mrkt_div_code,
                fid_cond_scr_div_code,
                fid_div_cls_code,
                fid_rank_sort_cls_code,
                fid_input_date_1,
                fid_input_date_2,
                fid_input_iscd,
                fid_trgt_cls_code,
                fid_aply_rang_vol,
                fid_aply_rang_prc_2,
                fid_aply_rang_prc_1,
                "N", dataframe, depth + 1, max_depth
            )
        else:
            logger.info("Data fetch complete.")
            return dataframe
    else:
        # API 에러 처리
        logger.error("API call failed: %s - %s", res.getErrorCode(), res.getErrorMessage())
        res.printError(API_URL)
        return pd.DataFrame()
