"""Stock name change history interface.

Fetch historical name change records for stocks.
This interface retrieves all historical name changes including name, dates, and change reasons.
"""

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


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


def get_namechange(
    ts_code: Optional[str] = None,
    start_date: Optional[str] = None,
    end_date: Optional[str] = None,
    fields: Optional[List[str]] = None,
) -> pd.DataFrame:
    """Fetch stock name change history.

    This interface retrieves historical name change records for stocks,
    including name, start/end dates, announcement date, and change reason.

    Args:
        ts_code: TS stock code (optional, if not provided, returns all stocks)
        start_date: Start date for announcement date range (YYYYMMDD)
        end_date: End date for announcement date range (YYYYMMDD)
        fields: Specific fields to return, None returns all fields

    Returns:
        pd.DataFrame with namechange information containing:
        - ts_code: TS stock code
        - name: Security name
        - start_date: Start date of the name
        - end_date: End date of the name
        - ann_date: Announcement date
        - change_reason: Reason for name change
    """
    client = TushareClient()

    # Build parameters
    params = {}
    if ts_code:
        params["ts_code"] = ts_code
    if start_date:
        params["start_date"] = start_date
    if end_date:
        params["end_date"] = end_date
    if fields:
        params["fields"] = ",".join(fields)

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

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

    return data


def sync_namechange(force: bool = False) -> pd.DataFrame:
    """Fetch and save all stock name change records to local CSV.

    This is a full load interface - fetches all historical name change records.
    Each call fetches all data (no incremental sync).

    Args:
        force: If True, force re-fetch even if CSV exists (default: False)

    Returns:
        pd.DataFrame with all namechange records
    """
    csv_path = _get_csv_path()

    # Check if CSV file already exists
    if csv_path.exists() and not force:
        print(f"[sync_namechange] namechange.csv already exists at {csv_path}")
        print("[sync_namechange] Use force=True to re-fetch")
        return pd.read_csv(csv_path, encoding="utf-8-sig")

    print("[sync_namechange] Fetching all stock name changes...")

    # Fetch all namechange data (no parameters = all stocks, all history)
    client = TushareClient()
    data = client.query("namechange")

    if data.empty:
        print("[sync_namechange] No namechange data fetched")
        return pd.DataFrame()

    print(f"[sync_namechange] Fetched {len(data)} name change records")

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


if __name__ == "__main__":
    # Sync all namechange records to data folder
    result = sync_namechange()
    print(f"Total records synced: {len(result)}")
    if not result.empty:
        print("\nSample data:")
        print(result.head(10))
