File size: 23,104 Bytes
e7427b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
// Knowledge Vault of Indian Environmental Laws, Policies, and IS Codes
// Comprehensive offline reference system for environmental compliance

interface LegalDocument {
  id: string;
  title: string;
  type: 'act' | 'rule' | 'policy' | 'standard' | 'guideline' | 'notification';
  authority: string;
  year: number;
  status: 'active' | 'amended' | 'superseded';
  summary: string;
  keyProvisions: string[];
  applicableTo: string[];
  penalties: string[];
  references: string[];
  lastUpdated: Date;
}

interface ISCode {
  code: string;
  title: string;
  category: string;
  year: number;
  status: 'current' | 'revised' | 'withdrawn';
  scope: string;
  keyRequirements: string[];
  testMethods: string[];
  applicableIndustries: string[];
  relatedCodes: string[];
}

interface ComplianceCheck {
  parameter: string;
  value: number;
  unit: string;
  applicable: LegalDocument[];
  compliance: 'compliant' | 'non_compliant' | 'marginal';
  recommendations: string[];
  nextReview: Date;
}

class KnowledgeVault {
  private legalDocuments: Map<string, LegalDocument> = new Map();
  private isCodes: Map<string, ISCode> = new Map();
  private searchIndex: Map<string, string[]> = new Map();

  constructor() {
    this.initializeLegalDatabase();
    this.initializeISCodes();
    this.buildSearchIndex();
  }

  // Search for legal documents
  searchLegalDocuments(query: string, filters?: {
    type?: LegalDocument['type'];
    authority?: string;
    year?: number;
  }): LegalDocument[] {
    try {
      if (!query || query.trim().length === 0) {
        return this.getAllDocuments(filters);
      }

      const searchTerms = query.toLowerCase().split(' ').filter(term => term.length > 2);
      const results = new Set<string>();

      // Search in index
      searchTerms.forEach(term => {
        const matches = this.searchIndex.get(term) || [];
        matches.forEach(docId => results.add(docId));
      });

      let documents = Array.from(results)
        .map(id => this.legalDocuments.get(id))
        .filter((doc): doc is LegalDocument => doc !== undefined);

      // Apply filters
      if (filters) {
        documents = documents.filter(doc => {
          if (filters.type && doc.type !== filters.type) return false;
          if (filters.authority && !doc.authority.toLowerCase().includes(filters.authority.toLowerCase())) return false;
          if (filters.year && doc.year !== filters.year) return false;
          return true;
        });
      }

      return documents.sort((a, b) => b.year - a.year);
    } catch (error) {
      throw new Error(`Failed to search legal documents: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  // Search IS Codes
  searchISCodes(query: string, category?: string): ISCode[] {
    try {
      if (!query || query.trim().length === 0) {
        const allCodes = Array.from(this.isCodes.values());
        return category 
          ? allCodes.filter(code => code.category.toLowerCase().includes(category.toLowerCase()))
          : allCodes;
      }

      const searchTerm = query.toLowerCase();
      return Array.from(this.isCodes.values()).filter(code =>
        code.code.toLowerCase().includes(searchTerm) ||
        code.title.toLowerCase().includes(searchTerm) ||
        code.scope.toLowerCase().includes(searchTerm) ||
        (category && code.category.toLowerCase().includes(category.toLowerCase()))
      ).sort((a, b) => b.year - a.year);
    } catch (error) {
      throw new Error(`Failed to search IS codes: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  // Check compliance for specific parameters
  checkCompliance(parameter: string, value: number, unit: string, context?: {
    industryType?: string;
    location?: string;
    dischargeTo?: string;
  }): ComplianceCheck {
    try {
      if (typeof value !== 'number' || isNaN(value)) {
        throw new Error('Invalid parameter value');
      }

      const applicableDocs = this.getApplicableRegulations(parameter, context);
      const limits = this.extractLimits(parameter, applicableDocs);
      
      let compliance: ComplianceCheck['compliance'] = 'compliant';
      const recommendations: string[] = [];

      // Check against limits
      for (const limit of limits) {
        if (value > limit.maxValue) {
          compliance = 'non_compliant';
          recommendations.push(`Exceeds ${limit.standard} limit of ${limit.maxValue} ${unit}`);
        } else if (value > limit.maxValue * 0.8) {
          compliance = 'marginal';
          recommendations.push(`Approaching ${limit.standard} limit - monitor closely`);
        }
      }

      if (compliance === 'compliant') {
        recommendations.push('Parameter within acceptable limits');
      }

      const nextReview = new Date();
      nextReview.setMonth(nextReview.getMonth() + 6); // 6 months from now

      return {
        parameter,
        value,
        unit,
        applicable: applicableDocs,
        compliance,
        recommendations,
        nextReview
      };
    } catch (error) {
      throw new Error(`Failed to check compliance: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  // Get applicable regulations for parameter
  getApplicableRegulations(parameter: string, context?: any): LegalDocument[] {
    const parameterKey = parameter.toLowerCase();
    const regulations: LegalDocument[] = [];

    this.legalDocuments.forEach(doc => {
      const isApplicable = doc.keyProvisions.some(provision =>
        provision.toLowerCase().includes(parameterKey) ||
        provision.toLowerCase().includes('water') ||
        provision.toLowerCase().includes('air') ||
        provision.toLowerCase().includes('emission')
      );

      if (isApplicable) {
        regulations.push(doc);
      }
    });

    return regulations;
  }

  // Get environmental clearance requirements
  getEnvironmentalClearanceInfo(projectType: string, projectCapacity?: number): {
    category: 'A' | 'B1' | 'B2' | 'exempted';
    authority: string;
    requirements: string[];
    timeline: string;
    fees: string;
    validity: string;
  } {
    try {
      const projectTypeLower = projectType.toLowerCase();
      
      // Simplified categorization based on EIA Notification 2006
      let category: 'A' | 'B1' | 'B2' | 'exempted';
      let authority: string;
      let requirements: string[];
      let timeline: string;
      let fees: string;

      if (projectTypeLower.includes('thermal power') && (projectCapacity || 0) >= 500) {
        category = 'A';
        authority = 'MoEF&CC, New Delhi';
        timeline = '210 days';
        fees = '₹5-50 lakhs';
      } else if (projectTypeLower.includes('cement') && (projectCapacity || 0) >= 1.0) {
        category = 'A';
        authority = 'MoEF&CC, New Delhi';
        timeline = '210 days';
        fees = '₹10-25 lakhs';
      } else if (projectTypeLower.includes('steel') || projectTypeLower.includes('iron')) {
        category = (projectCapacity || 0) >= 5.0 ? 'A' : 'B1';
        authority = category === 'A' ? 'MoEF&CC, New Delhi' : 'State Environment Impact Assessment Authority';
        timeline = category === 'A' ? '210 days' : '105 days';
        fees = category === 'A' ? '₹15-40 lakhs' : '₹2-10 lakhs';
      } else {
        category = 'B2';
        authority = 'State Environment Impact Assessment Authority';
        timeline = '105 days';
        fees = '₹50,000-5 lakhs';
      }

      requirements = this.getECRequirements(category);

      return {
        category,
        authority,
        requirements,
        timeline,
        fees,
        validity: '30 years (renewable)'
      };
    } catch (error) {
      throw new Error(`Failed to get EC information: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  // Get consent to operate requirements
  getConsentRequirements(industryType: string, pollutionCategory: 'red' | 'orange' | 'green' | 'white'): {
    authority: string;
    validity: string;
    requirements: string[];
    fees: string;
    monitoring: string[];
  } {
    try {
      const requirements = [
        'Valid Environmental Clearance (if applicable)',
        'Consent to Establish',
        'Pollution control equipment installation certificates',
        'Effluent/emission monitoring reports',
        'Waste management plan',
        'Emergency response plan'
      ];

      const monitoring = [
        'Monthly stack emission monitoring',
        'Daily effluent monitoring',
        'Quarterly ambient air quality monitoring',
        'Annual environmental audit'
      ];

      let validity: string;
      let fees: string;

      switch (pollutionCategory) {
        case 'red':
          validity = '5 years';
          fees = '₹25,000-10 lakhs';
          monitoring.push('Continuous emission monitoring system (CEMS)');
          break;
        case 'orange':
          validity = '5 years';
          fees = '₹10,000-5 lakhs';
          break;
        case 'green':
          validity = '5 years';
          fees = '₹5,000-1 lakh';
          break;
        default:
          validity = '5 years';
          fees = '₹2,500-25,000';
      }

      return {
        authority: 'State Pollution Control Board',
        validity,
        requirements,
        fees,
        monitoring
      };
    } catch (error) {
      throw new Error(`Failed to get consent requirements: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  // Export knowledge base
  exportKnowledgeBase(): string {
    try {
      const exportData = {
        legalDocuments: Array.from(this.legalDocuments.values()),
        isCodes: Array.from(this.isCodes.values()),
        exportDate: new Date().toISOString(),
        version: '1.0'
      };

      return JSON.stringify(exportData, null, 2);
    } catch (error) {
      throw new Error(`Failed to export knowledge base: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  // Private initialization methods
  private initializeLegalDatabase(): void {
    // Water-related regulations
    this.addLegalDocument({
      id: 'water_act_1974',
      title: 'Water (Prevention and Control of Pollution) Act, 1974',
      type: 'act',
      authority: 'Parliament of India',
      year: 1974,
      status: 'active',
      summary: 'Provides for the prevention and control of water pollution and maintaining or restoring of wholesomeness of water.',
      keyProvisions: [
        'Prohibition of discharge of pollutants into water bodies without consent',
        'Establishment of Central and State Pollution Control Boards',
        'Power to take samples and analyze water',
        'Penalties for violation of provisions'
      ],
      applicableTo: ['Industries', 'Municipalities', 'Commercial establishments'],
      penalties: ['Imprisonment up to 6 years', 'Fine up to ₹1 lakh', 'Daily fine of ₹5,000'],
      references: ['Water Act 1974', 'Water Rules 1975']
    });

    this.addLegalDocument({
      id: 'air_act_1981',
      title: 'Air (Prevention and Control of Pollution) Act, 1981',
      type: 'act',
      authority: 'Parliament of India',
      year: 1981,
      status: 'active',
      summary: 'Provides for the prevention, control and abatement of air pollution.',
      keyProvisions: [
        'Prohibition of air polluting industries in air pollution control areas',
        'Consent required for establishment and operation',
        'Power to give directions for closure of industries',
        'Standards for emission of air pollutants'
      ],
      applicableTo: ['Industries', 'Vehicles', 'Commercial establishments'],
      penalties: ['Imprisonment up to 6 years', 'Fine up to ₹1 lakh', 'Daily fine of ₹5,000'],
      references: ['Air Act 1981', 'Air Rules 1982']
    });

    this.addLegalDocument({
      id: 'environment_protection_act_1986',
      title: 'Environment (Protection) Act, 1986',
      type: 'act',
      authority: 'Parliament of India',
      year: 1986,
      status: 'active',
      summary: 'Umbrella legislation providing for protection and improvement of environment.',
      keyProvisions: [
        'General powers to Central Government for environmental protection',
        'Appointment of officers and authorities',
        'Power to direct closure of industries',
        'Environmental standards and guidelines'
      ],
      applicableTo: ['All activities affecting environment'],
      penalties: ['Imprisonment up to 5 years', 'Fine up to ₹1 lakh', 'Daily fine'],
      references: ['EPA 1986', 'Environment Rules 1986']
    });

    this.addLegalDocument({
      id: 'eia_notification_2006',
      title: 'Environmental Impact Assessment Notification, 2006',
      type: 'notification',
      authority: 'Ministry of Environment, Forest and Climate Change',
      year: 2006,
      status: 'amended',
      summary: 'Mandates prior environmental clearance for specified activities.',
      keyProvisions: [
        'Categorization of projects (Category A and B)',
        'Screening and scoping procedures',
        'Public consultation requirements',
        'Monitoring and compliance procedures'
      ],
      applicableTo: ['Mining', 'Thermal power', 'Industrial projects', 'Infrastructure'],
      penalties: ['Project closure', 'Penalty up to ₹1 crore', 'Legal action'],
      references: ['EIA Notification 2006', 'EIA Amendment 2020']
    });

    this.addLegalDocument({
      id: 'swm_rules_2016',
      title: 'Solid Waste Management Rules, 2016',
      type: 'rule',
      authority: 'Ministry of Environment, Forest and Climate Change',
      year: 2016,
      status: 'active',
      summary: 'Comprehensive rules for management of solid waste.',
      keyProvisions: [
        'Waste segregation at source',
        'Extended producer responsibility',
        'Processing and treatment of waste',
        'Waste to energy recovery'
      ],
      applicableTo: ['Urban local bodies', 'Waste generators', 'Bulk generators'],
      penalties: ['Fine as per local bye-laws', 'Spot fine up to ₹500'],
      references: ['SWM Rules 2016', 'SWM Amendment 2018']
    });

    this.addLegalDocument({
      id: 'hwm_rules_2016',
      title: 'Hazardous and Other Wastes Management Rules, 2016',
      type: 'rule',
      authority: 'Ministry of Environment, Forest and Climate Change',
      year: 2016,
      status: 'active',
      summary: 'Rules for management of hazardous and other wastes.',
      keyProvisions: [
        'Authorization for hazardous waste management',
        'Manifest system for waste tracking',
        'Treatment and disposal standards',
        'Liability and compensation provisions'
      ],
      applicableTo: ['Industries generating hazardous waste', 'Treatment facilities'],
      penalties: ['Closure directions', 'Fine up to ₹1 crore', 'Criminal liability'],
      references: ['HWM Rules 2016', 'HWM Amendment 2019']
    });
  }

  private initializeISCodes(): void {
    // Water quality standards
    this.addISCode({
      code: 'IS 10500:2012',
      title: 'Drinking Water — Specification',
      category: 'Water Quality',
      year: 2012,
      status: 'current',
      scope: 'Specifies requirements for drinking water quality',
      keyRequirements: [
        'pH: 6.5-8.5',
        'TDS: 500 mg/L (acceptable), 2000 mg/L (permissible)',
        'Turbidity: 1 NTU (acceptable), 5 NTU (permissible)',
        'Chloride: 250 mg/L (acceptable), 1000 mg/L (permissible)'
      ],
      testMethods: ['IS 3025 series for water testing'],
      applicableIndustries: ['Water supply', 'Bottled water', 'Food industry'],
      relatedCodes: ['IS 3025', 'IS 14543']
    });

    this.addISCode({
      code: 'IS 3025:2009',
      title: 'Methods of Sampling and Test (Physical and Chemical) for Water and Wastewater',
      category: 'Testing Methods',
      year: 2009,
      status: 'current',
      scope: 'Standard methods for water and wastewater analysis',
      keyRequirements: [
        'Sample collection procedures',
        'Preservation techniques',
        'Analytical methods for various parameters',
        'Quality control measures'
      ],
      testMethods: ['Gravimetric', 'Titrimetric', 'Spectrophotometric', 'Chromatographic'],
      applicableIndustries: ['Laboratories', 'Water treatment', 'Environmental monitoring'],
      relatedCodes: ['IS 10500', 'IS 2490']
    });

    // Air quality standards
    this.addISCode({
      code: 'IS 5182:2006',
      title: 'Methods for Measurement of Air Pollution',
      category: 'Air Quality',
      year: 2006,
      status: 'current',
      scope: 'Methods for measurement of ambient air quality',
      keyRequirements: [
        'Sampling methods for particulate matter',
        'Gas sampling techniques',
        'Calibration procedures',
        'Data validation methods'
      ],
      testMethods: ['Gravimetric analysis', 'Spectrophotometry', 'Gas chromatography'],
      applicableIndustries: ['Environmental monitoring', 'Industrial hygiene', 'Research'],
      relatedCodes: ['IS 11255', 'IS 9969']
    });

    // Structural codes
    this.addISCode({
      code: 'IS 456:2000',
      title: 'Plain and Reinforced Concrete - Code of Practice',
      category: 'Structural Engineering',
      year: 2000,
      status: 'current',
      scope: 'Requirements for design and construction of concrete structures',
      keyRequirements: [
        'Material specifications',
        'Design methods and principles',
        'Construction practices',
        'Quality control requirements'
      ],
      testMethods: ['Concrete strength testing', 'Durability tests', 'Non-destructive testing'],
      applicableIndustries: ['Construction', 'Infrastructure', 'Industrial structures'],
      relatedCodes: ['IS 875', 'IS 1893', 'IS 13920']
    });

    this.addISCode({
      code: 'IS 875:1987',
      title: 'Code of Practice for Design Loads (Other than Earthquake) for Buildings and Structures',
      category: 'Structural Engineering',
      year: 1987,
      status: 'current',
      scope: 'Design loads for buildings and structures',
      keyRequirements: [
        'Dead load calculations',
        'Live load specifications',
        'Wind load calculations',
        'Snow load considerations'
      ],
      testMethods: ['Load testing', 'Material property testing'],
      applicableIndustries: ['Building construction', 'Industrial structures', 'Infrastructure'],
      relatedCodes: ['IS 456', 'IS 800', 'IS 1893']
    });

    // Environmental engineering codes
    this.addISCode({
      code: 'IS 4764:2017',
      title: 'Code of Practice for Concrete Structures for the Storage of Liquids',
      category: 'Environmental Engineering',
      year: 2017,
      status: 'current',
      scope: 'Design and construction of liquid storage structures',
      keyRequirements: [
        'Structural design criteria',
        'Waterproofing requirements',
        'Joint design and sealing',
        'Quality control procedures'
      ],
      testMethods: ['Water tightness testing', 'Structural load testing'],
      applicableIndustries: ['Water treatment', 'Chemical storage', 'Sewage treatment'],
      relatedCodes: ['IS 456', 'IS 3370', 'IS 875']
    });
  }

  private addLegalDocument(doc: Omit<LegalDocument, 'lastUpdated'>): void {
    const document: LegalDocument = {
      ...doc,
      lastUpdated: new Date()
    };
    this.legalDocuments.set(doc.id, document);
  }

  private addISCode(code: ISCode): void {
    this.isCodes.set(code.code, code);
  }

  private buildSearchIndex(): void {
    // Build search index for legal documents
    this.legalDocuments.forEach(doc => {
      const searchableText = [
        doc.title,
        doc.summary,
        ...doc.keyProvisions,
        ...doc.applicableTo
      ].join(' ').toLowerCase();

      const words = searchableText.split(/\W+/).filter(word => word.length > 2);
      
      words.forEach(word => {
        if (!this.searchIndex.has(word)) {
          this.searchIndex.set(word, []);
        }
        const docIds = this.searchIndex.get(word)!;
        if (!docIds.includes(doc.id)) {
          docIds.push(doc.id);
        }
      });
    });
  }

  private getAllDocuments(filters?: any): LegalDocument[] {
    let documents = Array.from(this.legalDocuments.values());
    
    if (filters) {
      documents = documents.filter(doc => {
        if (filters.type && doc.type !== filters.type) return false;
        if (filters.authority && !doc.authority.toLowerCase().includes(filters.authority.toLowerCase())) return false;
        if (filters.year && doc.year !== filters.year) return false;
        return true;
      });
    }
    
    return documents.sort((a, b) => b.year - a.year);
  }

  private extractLimits(parameter: string, documents: LegalDocument[]): Array<{
    standard: string;
    maxValue: number;
    unit: string;
  }> {
    // Simplified limit extraction - in a real implementation, this would parse the documents
    const limits: Array<{ standard: string; maxValue: number; unit: string }> = [];
    
    const paramLower = parameter.toLowerCase();
    
    if (paramLower.includes('ph')) {
      limits.push({ standard: 'IS 10500:2012', maxValue: 8.5, unit: 'pH units' });
    } else if (paramLower.includes('bod')) {
      limits.push({ standard: 'CPCB Standards', maxValue: 30, unit: 'mg/L' });
    } else if (paramLower.includes('cod')) {
      limits.push({ standard: 'CPCB Standards', maxValue: 250, unit: 'mg/L' });
    } else if (paramLower.includes('tds')) {
      limits.push({ standard: 'IS 10500:2012', maxValue: 500, unit: 'mg/L' });
    } else if (paramLower.includes('pm2.5')) {
      limits.push({ standard: 'CPCB NAAQS', maxValue: 40, unit: 'μg/m³' });
    } else if (paramLower.includes('pm10')) {
      limits.push({ standard: 'CPCB NAAQS', maxValue: 60, unit: 'μg/m³' });
    }
    
    return limits;
  }

  private getECRequirements(category: string): string[] {
    const baseRequirements = [
      'Project proposal with detailed technical specifications',
      'Environmental Impact Assessment report',
      'Environmental Management Plan',
      'Risk assessment and disaster management plan',
      'Details of public consultation (for Category A & B1)'
    ];

    if (category === 'A') {
      return [
        ...baseRequirements,
        'Approved Terms of Reference from MoEF&CC',
        'Comprehensive EIA by accredited consultants',
        'Expert Appraisal Committee presentation',
        'State government recommendation'
      ];
    } else if (category === 'B1') {
      return [
        ...baseRequirements,
        'State level expert appraisal',
        'District Collector certificate'
      ];
    } else {
      return [
        'Simplified project information',
        'Environmental clearance from SEIAA',
        'No public consultation required'
      ];
    }
  }
}

export const knowledgeVault = new KnowledgeVault();
export { LegalDocument, ISCode, ComplianceCheck };