# [국내주식] 종목정보 - 국내주식 증권사별 투자의견
# Generated by KIS API Generator (Single API Mode)
# -*- coding: utf-8 -*-
"""
Created on 2025-06-17

"""

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

##############################################################################################
# [국내주식] 종목정보 > 국내주식 증권사별 투자의견[국내주식-189]
##############################################################################################

# 상수 정의
API_URL = "/uapi/domestic-stock/v1/quotations/invest-opbysec"

def invest_opbysec(
        fid_cond_mrkt_div_code: str,  # 조건시장분류코드
        fid_cond_scr_div_code: str,  # 조건화면분류코드
        fid_input_iscd: str,  # 입력종목코드
        fid_div_cls_code: str,  # 분류구분코드
        fid_input_date_1: str,  # 입력날짜1
        fid_input_date_2: str,  # 입력날짜2
        tr_cont: str = "",  # 연속 거래 여부
        dataframe: Optional[pd.DataFrame] = None,  # 누적 데이터프레임
        depth: int = 0,  # 현재 재귀 깊이
        max_depth: int = 10  # 최대 재귀 깊이
) -> Optional[pd.DataFrame]:
    """
    [국내주식] 종목정보 
    국내주식 증권사별 투자의견[국내주식-189]
    국내주식 증권사별 투자의견 API를 호출하여 DataFrame으로 반환합니다.
    
    Args:
        fid_cond_mrkt_div_code (str): J(시장 구분 코드)
        fid_cond_scr_div_code (str): 16634(Primary key)
        fid_input_iscd (str): 회원사코드 (kis developers 포탈 사이트 포럼-> FAQ -> 종목정보 다운로드(국내) 참조)
        fid_div_cls_code (str): 전체(0) 매수(1) 중립(2) 매도(3)
        fid_input_date_1 (str): 이후 ~
        fid_input_date_2 (str): ~ 이전
        tr_cont (str): 연속 거래 여부
        dataframe (Optional[pd.DataFrame]): 누적 데이터프레임
        depth (int): 현재 재귀 깊이
        max_depth (int): 최대 재귀 깊이 (기본값: 10)
        
    Returns:
        Optional[pd.DataFrame]: 국내주식 증권사별 투자의견 데이터
        
    Example:
        >>> df = invest_opbysec(
        ...     fid_cond_mrkt_div_code="J",
        ...     fid_cond_scr_div_code="16634",
        ...     fid_input_iscd="005930",
        ...     fid_div_cls_code="0",
        ...     fid_input_date_1="20230101",
        ...     fid_input_date_2="20231231"
        ... )
        >>> print(df)
    """
    # 로깅 설정
    logger = logging.getLogger(__name__)

    # 필수 파라미터 검증
    if not fid_cond_mrkt_div_code:
        logger.error("fid_cond_mrkt_div_code is required. (e.g. 'J')")
        raise ValueError("fid_cond_mrkt_div_code is required. (e.g. 'J')")

    if not fid_cond_scr_div_code:
        logger.error("fid_cond_scr_div_code is required. (e.g. '16634')")
        raise ValueError("fid_cond_scr_div_code is required. (e.g. '16634')")

    if not fid_input_iscd:
        logger.error("fid_input_iscd is required. (e.g. '005930')")
        raise ValueError("fid_input_iscd is required. (e.g. '005930')")

    if not fid_div_cls_code:
        logger.error("fid_div_cls_code is required. (e.g. '0')")
        raise ValueError("fid_div_cls_code is required. (e.g. '0')")

    if not fid_input_date_1:
        logger.error("fid_input_date_1 is required. (e.g. '20230101')")
        raise ValueError("fid_input_date_1 is required. (e.g. '20230101')")

    if not fid_input_date_2:
        logger.error("fid_input_date_2 is required. (e.g. '20231231')")
        raise ValueError("fid_input_date_2 is required. (e.g. '20231231')")

    # 최대 재귀 깊이 체크
    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()

    # API 호출 URL 및 거래 ID 설정

    tr_id = "FHKST663400C0"

    # API 요청 파라미터 설정
    params = {
        "FID_COND_MRKT_DIV_CODE": fid_cond_mrkt_div_code,
        "FID_COND_SCR_DIV_CODE": fid_cond_scr_div_code,
        "FID_INPUT_ISCD": fid_input_iscd,
        "FID_DIV_CLS_CODE": fid_div_cls_code,
        "FID_INPUT_DATE_1": fid_input_date_1,
        "FID_INPUT_DATE_2": fid_input_date_2,
    }

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

    # API 응답 처리
    if res.isOK():
        if hasattr(res.getBody(), 'output'):
            output_data = res.getBody().output
            if not isinstance(output_data, list):
                output_data = [output_data]
            current_data = pd.DataFrame(output_data)
        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 invest_opbysec(
                fid_cond_mrkt_div_code,
                fid_cond_scr_div_code,
                fid_input_iscd,
                fid_div_cls_code,
                fid_input_date_1,
                fid_input_date_2,
                "N", dataframe, depth + 1, max_depth
            )
        else:
            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()
