import * as FileSystem from 'expo-file-system';

import type { PlantIdentificationResult } from '../types/plantScan';

const scanStorageDir = `${FileSystem.documentDirectory || ''}pixiesprout-garden/`;
const scanResultsPath = `${scanStorageDir}plant-scan-results.json`;

async function ensureScanStorageDir() {
  if (!FileSystem.documentDirectory) return;
  const info = await FileSystem.getInfoAsync(scanStorageDir);
  if (!info.exists) {
    await FileSystem.makeDirectoryAsync(scanStorageDir, { intermediates: true });
  }
}

async function readScanResults(): Promise<PlantIdentificationResult[]> {
  try {
    if (!FileSystem.documentDirectory) return [];
    const info = await FileSystem.getInfoAsync(scanResultsPath);
    if (!info.exists) return [];
    const state = JSON.parse(await FileSystem.readAsStringAsync(scanResultsPath)) as { scans?: PlantIdentificationResult[] };
    return Array.isArray(state.scans) ? state.scans : [];
  } catch {
    return [];
  }
}

async function writeScanResults(scans: PlantIdentificationResult[]) {
  if (!FileSystem.documentDirectory) return;
  await ensureScanStorageDir();
  await FileSystem.writeAsStringAsync(scanResultsPath, JSON.stringify({ scans }));
}

export async function savePlantScanResult(scan: PlantIdentificationResult): Promise<PlantIdentificationResult> {
  const scans = await readScanResults();
  const nextScans = [scan, ...scans.filter(item => item.id !== scan.id)];
  await writeScanResults(nextScans);
  return scan;
}

export async function updatePlantScanResult(scanId: string, patch: Partial<PlantIdentificationResult>): Promise<PlantIdentificationResult | null> {
  const scans = await readScanResults();
  const existing = scans.find(item => item.id === scanId);
  if (!existing) return null;
  const updated = { ...existing, ...patch };
  await writeScanResults(scans.map(item => item.id === scanId ? updated : item));
  return updated;
}
