"""Simplified stock basic information interface.

Fetch basic stock information including code, name, listing date, etc.
This is a special interface - call once to get all stocks (listed and delisted).
"""

import os
import pandas as pd
from pathlib import Path
from typing import Optional, Literal, List
from src.data.client import TushareClient
from src.config.settings import get_settings


# CSV file path for stock basic data
def _get_csv_path() -> Path:
    """Get the CSV file path for stock basic data."""
    cfg = get_settings()
    return cfg.data_path_resolved / "stock_basic.csv"


def get_stock_basic(
    ts_code: Optional[str] = None,
    name: Optional[str] = None,
    market: Optional[Literal["主板", "创业板", "科创板", "CDR", "北交所"]] = None,
    list_status: Optional[Literal["L", "D", "P", "G"]] = None,
    exchange: Optional[Literal["SSE", "SZSE", "BSE"]] = None,
    is_hs: Optional[Literal["N", "H", "S"]] = None,
    fields: Optional[List[str]] = None,
) -> pd.DataFrame:
    """Fetch basic stock information.

    This interface retrieves basic information data including stock code,
    name, listing date, delisting date, etc.

    Args:
        ts_code: TS stock code
        name: Stock name
        market: Market type (主板/创业板/科创板/CDR/北交所)
        list_status: Listing status - L(listed), D(delisted), P(paused), G(approved-not-traded)
        exchange: Exchange - SSE, SZSE, BSE
        is_hs: HS indicator - N(no), H(Shanghai), S(Shenzhen)
        fields: Specific fields to return, None returns default fields

    Returns:
        pd.DataFrame with stock basic information containing:
        - ts_code, symbol, name, area, industry, fullname, enname, cnspell,
          market, exchange, curr_type, list_status, list_date, delist_date,
          is_hs, act_name, act_ent_type
    """
    client = TushareClient()

    # Build parameters
    params = {}
    if ts_code:
        params["ts_code"] = ts_code
    if name:
        params["name"] = name
    if market:
        params["market"] = market
    if list_status:
        params["list_status"] = list_status
    if exchange:
        params["exchange"] = exchange
    if is_hs:
        params["is_hs"] = is_hs
    if fields:
        params["fields"] = ",".join(fields)

    # Fetch data
    data = client.query("stock_basic", **params)

    if data.empty:
        print("[get_stock_basic] No data returned")

    return data


def sync_all_stocks(
    force_full: bool = False,
    dry_run: bool = False,
    **kwargs,
) -> pd.DataFrame:
    """Fetch and save all stocks (listed and delisted) to local storage.

    This is a special interface that should only be called once to initialize
    the local database with all stock information.

    Returns:
        pd.DataFrame with all stock information
    """
    csv_path = _get_csv_path()

    # Check if CSV file already exists
    if csv_path.exists():
        print("[sync_all_stocks] stock_basic.csv already exists, skipping...")
        return pd.read_csv(csv_path)

    print("[sync_all_stocks] Fetching all stocks (listed and delisted)...")

    # Fetch all stocks - explicitly get all list_status values
    # API default is L (listed), so we need to fetch all statuses
    client = TushareClient()

    all_data = []
    for status in ["L", "D", "P", "G"]:
        print(f"[sync_all_stocks] Fetching stocks with status: {status}")
        data = client.query("stock_basic", list_status=status)
        print(f"[sync_all_stocks] Fetched {len(data)} stocks with status {status}")
        if not data.empty:
            all_data.append(data)

    if not all_data:
        print("[sync_all_stocks] No stock data fetched")
        return pd.DataFrame()

    # Combine all data
    data = pd.concat(all_data, ignore_index=True)
    # Remove duplicates if any
    data = data.drop_duplicates(subset=["ts_code"], keep="first")
    print(f"[sync_all_stocks] Total unique stocks: {len(data)}")

    # Save to CSV
    data.to_csv(csv_path, index=False, encoding="utf-8-sig")
    print(f"[sync_all_stocks] Saved {len(data)} stocks to {csv_path}")
    return data


if __name__ == "__main__":
    # Sync all stocks (listed and delisted) to data folder
    result = sync_all_stocks()
    print(f"Total stocks synced: {len(result)}")
