import { useParams, useSearchParams } from 'next/navigation';
import { useChinaFinancials, useFinancials, useFinancialConfig, useAnalysisTemplateSets, useSnapshot, useRealtimeQuote, useAnalysisResults } from '@/hooks/useApi';

export function useReportData() {
  const params = useParams();
  const searchParams = useSearchParams();
  const symbol = params.symbol as string;
  const marketParam = (searchParams.get('market') || '').toLowerCase();
  const normalizedMarket = (() => {
    if (marketParam === 'usa') return 'us';
    if (marketParam === 'china') return 'cn';
    if (marketParam === 'hkex') return 'hk';
    if (marketParam === 'jpn') return 'jp';
    return marketParam;
  })();

  const displayMarket = marketParam === 'china' ? '中国' : marketParam;

  const isChina = normalizedMarket === 'cn';

  // 规范化中国市场 ts_code：若为6位数字或无后缀，自动推断交易所
  const normalizedTsCode = (() => {
    if (!isChina) return symbol;
    if (!symbol) return symbol;
    if (symbol.includes('.')) return symbol.toUpperCase();
    const onlyDigits = symbol.replace(/\D/g, '');
    if (onlyDigits.length === 6) {
      const first = onlyDigits[0];
      if (first === '6') return `${onlyDigits}.SH`;
      if (first === '0' || first === '3') return `${onlyDigits}.SZ`;
    }
    return symbol.toUpperCase();
  })();

  const chinaFin = useChinaFinancials(isChina ? normalizedTsCode : undefined, 10);
  const otherFin = useFinancials(!isChina ? normalizedMarket : undefined, !isChina ? symbol : undefined, 10);
  const financials = (chinaFin.data ?? otherFin.data) as any;
  const error = chinaFin.error ?? otherFin.error;
  const isLoading = chinaFin.isLoading || otherFin.isLoading;
  const unifiedSymbol = isChina ? normalizedTsCode : symbol;
  const { data: snapshot, error: snapshotError, isLoading: snapshotLoading } = useSnapshot(normalizedMarket, unifiedSymbol);
  const { data: realtime, error: realtimeError, isLoading: realtimeLoading } = useRealtimeQuote(normalizedMarket, unifiedSymbol, { maxAgeSeconds: 30, refreshIntervalMs: 5000 });
  const { data: financialConfig } = useFinancialConfig();
  const { data: templateSets } = useAnalysisTemplateSets();
  const { data: historicalAnalysis } = useAnalysisResults(unifiedSymbol);

  return {
    symbol,
    unifiedSymbol,
    displayMarket,
    normalizedMarket,
    marketParam,
    financials,
    isLoading,
    error,
    snapshot,
    snapshotLoading,
    snapshotError,
    realtime,
    realtimeLoading,
    realtimeError,
    financialConfig: financialConfig as any,
    templateSets,
    historicalAnalysis
  };
}

