import Parser from "rss-parser";
import cron from "node-cron";

export interface RSSFeedConfig {
  url: string;
  interval: string; // cron 형식
}

export interface RSSDocument {
  title: string;
  link: string;
  content: string;
  pubDate: string;
  author?: string;
  categories?: string[];
  source: string;
}

export class RSSFetcher {
  private parser: Parser;
  private configs: RSSFeedConfig[];

  constructor(configs: RSSFeedConfig[]) {
    this.parser = new Parser();
    this.configs = configs;
  }

  public start() {
    this.configs.forEach((config) => {
      cron.schedule(config.interval, async () => {
        try {
          const feed = await this.parser.parseURL(config.url);
          const docs = feed.items.map((item) =>
            this.toDocument(item, config.url)
          );
          // TODO: 벡터스토어 저장 로직 연결
          console.log(`[${config.url}] Fetched ${docs.length} items.`);
        } catch (err) {
          console.error(`[${config.url}] Fetch error:`, err);
          // TODO: 재시도/로깅 구현
        }
      });
    });
  }

  private toDocument(item: Parser.Item, source: string): RSSDocument {
    return {
      title: item.title || "",
      link: item.link || "",
      content: item.contentSnippet || item.content || "",
      pubDate: item.pubDate || "",
      author: item.creator || (item as any).author,
      categories: item.categories || [],
      source,
    };
  }
}

// 사용 예시 (실제 서비스에서는 별도 config 파일/DB에서 불러올 것)
// const fetcher = new RSSFetcher([
//   { url: 'https://example.com/rss', interval: '0 * * * *' },
// ]);
// fetcher.start();
