import fs from 'fs';
import path from 'path';
import { Sport, League, Participant, WidgetType, Template, SeedData } from '../types';

class JsonDataStore {
  private sports: Sport[] = [];
  private leagues: League[] = [];
  private participants: Participant[] = [];
  private widgetTypes: WidgetType[] = [];
  private templates: Template[] = [];
  private loaded = false;

  load(): void {
    if (this.loaded) return;

    const seedPath = path.join(process.cwd(), 'sportpulse_widgets_seed.json');

    if (!fs.existsSync(seedPath)) {
      console.warn('Seed file not found, using empty data');
      this.loaded = true;
      return;
    }

    const rawData = fs.readFileSync(seedPath, 'utf-8');
    const seedData: SeedData = JSON.parse(rawData);

    // Load sports (map iconUrl to icon)
    this.sports = seedData.sports.map(s => ({
      id: s.id,
      sportName: s.sportName,
      icon: s.iconUrl,
      isActive: s.isActive,
      createdAt: new Date(),
      updatedAt: new Date(),
    }));

    // Load leagues (map iconUrl to leagueLogo)
    this.leagues = seedData.leagues.map(l => ({
      id: l.id,
      sportId: l.sportId,
      sportName: l.sportName,
      leagueName: l.leagueName,
      leagueLogo: l.iconUrl,
      isActive: l.isActive,
      createdAt: new Date(),
      updatedAt: new Date(),
    }));

    // Load participants (map teamLogoUrl to teamLogo)
    this.participants = seedData.participants.map(p => ({
      id: p.id,
      participantType: p.participantType,
      sportId: p.sportId,
      sportName: p.sportName,
      leagueIds: p.leagueIds,
      leagueNames: p.leagueNames,
      teamName: p.teamName,
      fullName: p.fullName,
      shortName: p.shortName,
      abbreviation: p.abbreviation,
      teamLogo: p.teamLogoUrl,
      isActive: p.isActive,
      createdAt: new Date(),
      updatedAt: new Date(),
    }));

    // Load widget types
    this.widgetTypes = seedData.widgetTypes.map(w => ({
      ...w,
      createdAt: new Date(),
      updatedAt: new Date(),
    }));

    // Load templates (map thumbnailDarkUrl/thumbnailLightUrl to thumbnailDark/thumbnailLight)
    this.templates = seedData.templates.map(t => ({
      id: t.id,
      sportId: t.sportId,
      sportName: t.sportName,
      leagueId: t.leagueId,
      leagueName: t.leagueName,
      participantId: t.participantId,
      teamName: t.teamName,
      widgetTypeId: t.widgetTypeId,
      widgetName: t.widgetName,
      templateName: t.templateName,
      darkThemeUrl: t.darkThemeUrl,
      lightThemeUrl: t.lightThemeUrl,
      thumbnailDark: t.thumbnailDarkUrl,
      thumbnailLight: t.thumbnailLightUrl,
      featured: t.featured,
      isActive: t.isActive,
      createdAt: new Date(),
      updatedAt: new Date(),
    }));

    this.loaded = true;
    console.log(`Loaded from JSON: ${this.sports.length} sports, ${this.leagues.length} leagues, ${this.widgetTypes.length} widget types, ${this.templates.length} templates`);
  }

  // Sports
  getSports(isActive?: boolean): Sport[] {
    this.load();
    let result = [...this.sports];
    if (isActive !== undefined) {
      result = result.filter(s => s.isActive === isActive);
    }
    return result.sort((a, b) => a.sportName.localeCompare(b.sportName));
  }

  getSportById(id: number): Sport | null {
    this.load();
    return this.sports.find(s => s.id === id) || null;
  }

  // Leagues
  getLeaguesBySportId(sportId: number, isActive?: boolean): League[] {
    this.load();
    let result = this.leagues.filter(l => l.sportId === sportId);
    if (isActive !== undefined) {
      result = result.filter(l => l.isActive === isActive);
    }
    return result.sort((a, b) => a.leagueName.localeCompare(b.leagueName));
  }

  getLeagueById(id: number): League | null {
    this.load();
    return this.leagues.find(l => l.id === id) || null;
  }

  // Participants
  getParticipantsByLeagueId(leagueId: number, type?: string, isActive?: boolean): Participant[] {
    this.load();
    let result = this.participants.filter(p => p.leagueIds.includes(leagueId));
    if (type) {
      result = result.filter(p => p.participantType === type);
    }
    if (isActive !== undefined) {
      result = result.filter(p => p.isActive === isActive);
    }
    return result.sort((a, b) =>
      (a.teamName || a.fullName || '').localeCompare(b.teamName || b.fullName || '')
    );
  }

  // Widget Types
  getWidgetTypes(sportId?: number, leagueId?: number, isActive?: boolean): WidgetType[] {
    this.load();
    let result = [...this.widgetTypes];
    if (sportId !== undefined) {
      result = result.filter(w => w.sportId === sportId);
    }
    if (leagueId !== undefined) {
      result = result.filter(w => w.leagueId === leagueId);
    }
    if (isActive !== undefined) {
      result = result.filter(w => w.isActive === isActive);
    }
    return result.sort((a, b) => a.widgetName.localeCompare(b.widgetName));
  }

  // Templates
  getTemplates(filters: {
    sportId?: number;
    leagueId?: number;
    widgetTypeId?: number;
    participantId?: number;
    featured?: boolean;
    isActive?: boolean;
  }): Template[] {
    this.load();
    let result = [...this.templates];

    if (filters.sportId !== undefined) {
      result = result.filter(t => t.sportId === filters.sportId);
    }
    if (filters.leagueId !== undefined) {
      result = result.filter(t => t.leagueId === filters.leagueId);
    }
    if (filters.widgetTypeId !== undefined) {
      result = result.filter(t => t.widgetTypeId === filters.widgetTypeId);
    }
    if (filters.participantId !== undefined) {
      result = result.filter(t => t.participantId === filters.participantId);
    }
    if (filters.featured !== undefined) {
      result = result.filter(t => t.featured === filters.featured);
    }
    if (filters.isActive !== undefined) {
      result = result.filter(t => t.isActive === filters.isActive);
    }

    return result.sort((a, b) => a.templateName.localeCompare(b.templateName));
  }
}

export const jsonStore = new JsonDataStore();
