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75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
import { WikimediaProject, SearchResult, StudyPlan } from '../types';

export const WIKIMEDIA_PROJECTS: WikimediaProject[] = [
  {
    id: 'wikipedia',
    name: 'Wikipedia',
    description: 'The free encyclopedia',
    apiUrl: 'https://en.wikipedia.org/w/api.php',
    color: 'bg-primary-500',
    icon: 'Book'
  },
  {
    id: 'wikibooks',
    name: 'Wikibooks',
    description: 'Free textbooks and manuals',
    apiUrl: 'https://en.wikibooks.org/w/api.php',
    color: 'bg-secondary-500',
    icon: 'BookOpen'
  },
  {
    id: 'wikiquote',
    name: 'Wikiquote',
    description: 'Collection of quotations',
    apiUrl: 'https://en.wikiquote.org/w/api.php',
    color: 'bg-accent-500',
    icon: 'Quote'
  },
  {
    id: 'wikiversity',
    name: 'Wikiversity',
    description: 'Free learning resources',
    apiUrl: 'https://en.wikiversity.org/w/api.php',
    color: 'bg-success-500',
    icon: 'GraduationCap'
  },
  {
    id: 'wiktionary',
    name: 'Wiktionary',
    description: 'Free dictionary',
    apiUrl: 'https://en.wiktionary.org/w/api.php',
    color: 'bg-warning-500',
    icon: 'Languages'
  },
  {
    id: 'wikisource',
    name: 'Wikisource',
    description: 'Free library of source texts',
    apiUrl: 'https://en.wikisource.org/w/api.php',
    color: 'bg-error-500',
    icon: 'FileText'
  }
];

export class WikimediaAPI {
  private static async makeRequest(apiUrl: string, params: Record<string, string>): Promise<any> {
    const url = new URL(apiUrl);
    Object.entries(params).forEach(([key, value]) => {
      url.searchParams.append(key, value);
    });

    try {
      const response = await fetch(url.toString());
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      console.error('API request failed:', error);
      throw error;
    }
  }

  static async search(query: string, project: string = 'wikipedia', limit: number = 10): Promise<SearchResult[]> {
    const projectData = WIKIMEDIA_PROJECTS.find(p => p.id === project);
    if (!projectData) {
      throw new Error(`Unknown project: ${project}`);
    }

    const params = {
      action: 'query',
      format: 'json',
      list: 'search',
      srsearch: query,
      srlimit: limit.toString(),
      srprop: 'snippet|titlesnippet|size|timestamp',
      origin: '*'
    };

    try {
      const data = await this.makeRequest(projectData.apiUrl, params);
      
      return data.query?.search?.map((result: any) => ({
        title: result.title,
        pageid: result.pageid,
        size: result.size,
        snippet: result.snippet || 'No snippet available',
        timestamp: result.timestamp,
        project: project,
        url: this.buildProjectUrl(project, result.title)
      })) || [];
    } catch (error) {
      console.error(`Search failed for ${project}:`, error);
      return [];
    }
  }

  static async searchMultipleProjects(query: string, projects: string[] = ['wikipedia', 'wikibooks', 'wikiversity'], limit: number = 5): Promise<SearchResult[]> {
    const searchPromises = projects.map(project => this.search(query, project, limit));
    
    try {
      const results = await Promise.allSettled(searchPromises);
      const allResults: SearchResult[] = [];
      
      results.forEach((result) => {
        if (result.status === 'fulfilled') {
          allResults.push(...result.value);
        }
      });
      
      return allResults.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
    } catch (error) {
      console.error('Multi-project search failed:', error);
      return [];
    }
  }

  static async getPageContent(title: string, project: string = 'wikipedia'): Promise<string> {
    const projectData = WIKIMEDIA_PROJECTS.find(p => p.id === project);
    if (!projectData) {
      throw new Error(`Unknown project: ${project}`);
    }

    // Handle language-specific Wikipedia projects
    let apiUrl = projectData.apiUrl;
    if (project.includes('-wikipedia')) {
      const langCode = project.split('-')[0];
      apiUrl = `https://${langCode}.wikipedia.org/w/api.php`;
    }

    // Try multiple approaches to get the best content
    const approaches = [
      // Approach 1: Get full extract
      {
        action: 'query',
        format: 'json',
        titles: title,
        prop: 'extracts',
        exintro: 'false',
        explaintext: 'true',
        exsectionformat: 'plain',
        origin: '*'
      },
      // Approach 2: Get intro only if full content fails
      {
        action: 'query',
        format: 'json',
        titles: title,
        prop: 'extracts',
        exintro: 'true',
        explaintext: 'true',
        exsentences: '10',
        origin: '*'
      }
    ];

    for (const params of approaches) {
      try {
        const data = await this.makeRequest(apiUrl, params);
        const pages = data.query?.pages || {};
        const pageId = Object.keys(pages)[0];
        
        if (pageId !== '-1' && pages[pageId]?.extract) {
          const content = pages[pageId].extract;
          if (content.length > 200) {
            return content;
          }
        }
      } catch (error) {
        console.log(`Approach failed for ${title}:`, error);
        continue;
      }
    }

    // Fallback: Return a helpful message
    const projectName = projectData.name;
    return `This article exists but the content could not be fully loaded through the API.

The article "${title}" is available on ${projectName}, but due to API limitations or the article's structure, we cannot display the full content here.

This might happen because:
- The article is a disambiguation page
- The content is primarily in tables, lists, or special formatting  
- The article has restricted content access
- There are temporary API limitations

For the complete article with all formatting, images, and references, please visit the original source using the "View Original" button.`;
  }

  static async getRandomArticles(project: string = 'wikipedia', count: number = 5): Promise<SearchResult[]> {
    const projectData = WIKIMEDIA_PROJECTS.find(p => p.id === project);
    if (!projectData) {
      throw new Error(`Unknown project: ${project}`);
    }

    const params = {
      action: 'query',
      format: 'json',
      list: 'random',
      rnnamespace: '0',
      rnlimit: count.toString(),
      origin: '*'
    };

    try {
      const data = await this.makeRequest(projectData.apiUrl, params);
      const randomPages = data.query?.random || [];
      
      // Get snippets for random articles
      const results: SearchResult[] = [];
      for (const page of randomPages) {
        try {
          const snippet = await this.getPageSnippet(page.title, project);
          results.push({
            title: page.title,
            pageid: page.id,
            size: 0,
            snippet: snippet,
            timestamp: new Date().toISOString(),
            project: project,
            url: this.buildProjectUrl(project, page.title)
          });
        } catch (error) {
          // If we can't get snippet, still include the article
          results.push({
            title: page.title,
            pageid: page.id,
            size: 0,
            snippet: `Random article from ${projectData.name}`,
            timestamp: new Date().toISOString(),
            project: project,
            url: this.buildProjectUrl(project, page.title)
          });
        }
      }
      
      return results;
    } catch (error) {
      console.error(`Failed to get random articles from ${project}:`, error);
      return [];
    }
  }

  private static async getPageSnippet(title: string, project: string): Promise<string> {
    const projectData = WIKIMEDIA_PROJECTS.find(p => p.id === project);
    if (!projectData) {
      return 'No description available';
    }

    const params = {
      action: 'query',
      format: 'json',
      titles: title,
      prop: 'extracts',
      exintro: 'true',
      explaintext: 'true',
      exsentences: '2',
      origin: '*'
    };

    try {
      const data = await this.makeRequest(projectData.apiUrl, params);
      const pages = data.query?.pages || {};
      const pageId = Object.keys(pages)[0];
      
      if (pageId === '-1') {
        return 'No description available';
      }

      const extract = pages[pageId]?.extract || 'No description available';
      return extract.length > 200 ? extract.substring(0, 200) + '...' : extract;
    } catch (error) {
      return 'No description available';
    }
  }

  static async generateStudyPlan(topic: string, difficulty: 'beginner' | 'intermediate' | 'advanced' = 'beginner'): Promise<StudyPlan> {
    try {
      // Search across multiple projects for comprehensive content
      const searchResults = await this.searchMultipleProjects(topic, ['wikipedia', 'wikibooks', 'wikiversity'], 15);
      
      if (searchResults.length === 0) {
        throw new Error('No content found for this topic');
      }

      // Filter and organize results
      const topicCount = difficulty === 'beginner' ? 5 : difficulty === 'intermediate' ? 8 : 12;
      const selectedResults = searchResults.slice(0, topicCount);

      // Generate study plan structure with real data
      const studyPlan: StudyPlan = {
        id: `plan-${Date.now()}`,
        title: `${topic} Study Plan`,
        description: `Comprehensive ${difficulty} level study plan for ${topic} using real Wikimedia content`,
        difficulty,
        estimatedTime: this.estimateStudyTime(selectedResults.length, difficulty),
        created: new Date().toISOString(),
        topics: await this.generateTopicsFromResults(selectedResults, difficulty)
      };

      return studyPlan;
    } catch (error) {
      console.error('Failed to generate study plan:', error);
      throw error;
    }
  }

  private static async generateTopicsFromResults(results: SearchResult[], difficulty: string): Promise<any[]> {
    const topics = [];
    
    for (let i = 0; i < results.length; i++) {
      const result = results[i];
      
      // Get more detailed content for each topic
      let detailedContent = result.snippet;
      try {
        const fullContent = await this.getPageSnippet(result.title, result.project);
        if (fullContent && fullContent !== 'No description available') {
          detailedContent = fullContent;
        }
      } catch (error) {
        console.log(`Could not get detailed content for ${result.title}`);
      }

      topics.push({
        id: `topic-${Date.now()}-${i}`,
        title: result.title,
        description: detailedContent.replace(/<[^>]*>/g, '').substring(0, 200) + '...',
        content: detailedContent,
        completed: false,
        estimatedTime: `${Math.ceil(Math.random() * 2 + 1)} hours`,
        resources: [
          {
            title: result.title,
            url: result.url,
            type: 'article' as const,
            project: result.project
          }
        ]
      });
    }
    
    return topics;
  }

  private static buildProjectUrl(project: string, title: string): string {
    const baseUrls: Record<string, string> = {
      wikipedia: 'https://en.wikipedia.org/wiki/',
      wikibooks: 'https://en.wikibooks.org/wiki/',
      wikiquote: 'https://en.wikiquote.org/wiki/',
      wikiversity: 'https://en.wikiversity.org/wiki/',
      wiktionary: 'https://en.wiktionary.org/wiki/',
      wikisource: 'https://en.wikisource.org/wiki/',
    };

    const baseUrl = baseUrls[project] || baseUrls.wikipedia;
    return baseUrl + encodeURIComponent(title.replace(/ /g, '_'));
  }

  private static estimateStudyTime(contentCount: number, difficulty: string): string {
    const baseHours = contentCount * 1.5; // More realistic time estimate
    const multiplier = difficulty === 'beginner' ? 1 : difficulty === 'intermediate' ? 1.5 : 2;
    const totalHours = Math.ceil(baseHours * multiplier);
    
    if (totalHours < 24) {
      return `${totalHours} hours`;
    } else {
      const weeks = Math.ceil(totalHours / 10); // Assuming 10 hours per week
      return `${weeks} weeks`;
    }
  }

  // Real-time progress tracking methods
  static getStoredProgress(): any {
    try {
      const stored = localStorage.getItem('wikistro-progress');
      return stored ? JSON.parse(stored) : this.getDefaultProgress();
    } catch (error) {
      return this.getDefaultProgress();
    }
  }

  static saveProgress(progressData: any): void {
    try {
      localStorage.setItem('wikistro-progress', JSON.stringify(progressData));
    } catch (error) {
      console.error('Failed to save progress:', error);
    }
  }

  static getStoredStudyPlans(): StudyPlan[] {
    try {
      const stored = localStorage.getItem('wikistro-study-plans');
      return stored ? JSON.parse(stored) : [];
    } catch (error) {
      return [];
    }
  }

  static saveStudyPlans(plans: StudyPlan[]): void {
    try {
      localStorage.setItem('wikistro-study-plans', JSON.stringify(plans));
    } catch (error) {
      console.error('Failed to save study plans:', error);
    }
  }

  private static getDefaultProgress() {
    return {
      studyStreak: 0,
      topicsCompleted: 0,
      totalStudyTime: 0,
      achievements: 0,
      weeklyGoal: { current: 0, target: 12 },
      recentActivity: [],
      completedTopics: [],
      lastStudyDate: null
    };
  }
}