
import os
import sys
import json
import requests
import time
from dotenv import load_dotenv

# Add src to path
sys.path.append(os.path.join(os.path.dirname(__file__), '../src'))

from fetchers.ifind_client import IFindClient

def debug_ifind():
    load_dotenv()
    token = os.getenv("IFIND_REFRESH_TOKEN")
    if not token:
        print("Missing IFIND_REFRESH_TOKEN in .env")
        return

    client = IFindClient(token)
    print(f"Loaded token: {token[:20]}... (Length: {len(token)})")
    
    # Try a simple token refresh check directly
    print("Testing token refresh...")
    access_token = client._get_access_token()
    if access_token:
        print(f"Success! Access Token: {access_token[:20]}...")
    else:
        print("Failed to get access token.")
        return
    symbol = "7203.T"
    
    print(f"--- Testing basic_data_service for {symbol} ---")
    params = {
        "codes": symbol,
        "indipara": [
            {"indicator": "revenue_oas", "indiparams": ["8", "1", "BB"]},
            {"indicator": "ths_reporting_period_stock", "indiparams": []}
        ]
    }
    res = client.post("basic_data_service", params)
    print(json.dumps(res, indent=2, ensure_ascii=False))

    print(f"\n--- Testing date_sequence Interval='Y' for {symbol} ---")
    end_date = time.strftime("%Y%m%d")
    start_date = "20220101"
    params_seq = {
        "codes": symbol,
        "startdate": start_date,
        "enddate": end_date,
        "functionpara": {"Interval": "Y", "Days": "Alldays", "Fill": "Previous"},
        "indipara": [
            {"indicator": "revenue_oas", "indiparams": ["8", "", "BB"]}
        ]
    }
    res_seq = client.post("date_sequence", params_seq)
    print(json.dumps(res_seq, indent=2, ensure_ascii=False))

    print(f"\n--- Testing cmd_history_quotation for {symbol} ---")
    params_hist = {
        "codes": symbol,
        "startdate": start_date,
        "enddate": end_date,
        "indicators": "close,totalCapital",
        "functionpara": {"Interval": "D", "Days": "Alldays", "Fill": "Previous"}
    }
    res_hist = client.post("cmd_history_quotation", params_hist)
    print(json.dumps(res_hist, indent=2, ensure_ascii=False))

    print(f"\n--- Testing date_sequence with standard indicators for {symbol} ---")
    params_std = {
        "codes": symbol,
        "startdate": start_date,
        "enddate": end_date,
        "functionpara": {"Interval": "D", "Days": "Alldays", "Fill": "Previous"},
        "indipara": [
            {"indicator": "total_mv", "indiparams": ["1", "BB"]},
            {"indicator": "pe_ttm", "indiparams": ["1", "BB"]}
        ]
    }
    print(f"\n--- Testing basic_data_service with specific dates for {symbol} ---")
    params_dates = {
        "codes": symbol,
        "indipara": [
            {"indicator": "revenue_oas", "indiparams": ["20240331", "", "BB"]},
            {"indicator": "revenue_oas", "indiparams": ["20230331", "", "BB"]}
        ]
    }
    res_dates = client.post("basic_data_service", params_dates)
    print(json.dumps(res_dates, indent=2, ensure_ascii=False))

if __name__ == "__main__":
    debug_ifind()
