import { mkdirSync, writeFileSync } from 'fs';
import { join } from 'path';
import { logger } from '../../logger.js';

export type BlockType = 'amazon_products' | 'map_places' | 'x_posts' | 'youtube_videos';

export interface StructuredBlock {
  refId: string;
  type: BlockType;
  title: string;
  data: unknown;
}

export interface AmazonProductData {
  query: string;
  products: AmazonProductItem[];
}

export interface AmazonProductItem {
  asin: string;
  title: string;
  price?: string;
  rating?: number;
  reviewCount?: number;
  imageUrl?: string;
  productUrl: string;
  keepaGraphUrl: string;
  keepaDetailUrl: string;
}

export interface MapPlaceItem {
  name: string;
  address: string;
  lat: number;
  lon: number;
  type: string;
  details: string;
  mapUrl: string;
}

export interface MapPlacesData {
  query: string;
  places: MapPlaceItem[];
}

export interface XPostItem {
  id: string;
  text: string;
  authorName: string;
  authorScreenName: string;
  authorImageUrl: string;
  likes: number;
  retweets: number;
  replies: number;
  views: number;
  createdAt: string;
  postUrl: string;
}

export interface XPostsData {
  query: string;
  posts: XPostItem[];
}

export interface YouTubeVideoItem {
  videoId: string;
  title: string;
  channelName: string;
  thumbnailUrl: string;
  videoUrl: string;
  viewCount: string;
  publishedAt: string;
  duration: string;
  description: string;
}

export interface YouTubeVideosData {
  query: string;
  videos: YouTubeVideoItem[];
}

/**
 * structuredBlocks を logs/structured/ に保存する。
 */
export function saveStructuredBlocks(workspacePath: string, blocks: StructuredBlock[]): void {
  if (!blocks.length) return;
  try {
    const dir = join(workspacePath, 'logs', 'structured');
    mkdirSync(dir, { recursive: true });
    for (const block of blocks) {
      const filePath = join(dir, `${block.refId}.json`);
      writeFileSync(filePath, JSON.stringify(block, null, 2), 'utf-8');
    }
  } catch (err) {
    logger.warn(`[structured-blocks] failed to save: ${err}`);
  }
}

