import { acquireScanPriority, releaseScanPriority } from '../plantIntelligence/photoIntelligenceExtractor';
import { logDev } from '../providerUtils';
import type { PlantIdentificationInput, PlantIdentificationResult } from './types';
import { xiaomiMimoProvider } from './xiaomiMimoProvider';

export type PlantIdentificationProvider = {
  name: string;
  identifyPlant(input: PlantIdentificationInput): Promise<PlantIdentificationResult>;
};

let activeProvider: PlantIdentificationProvider = xiaomiMimoProvider;

export function setPlantIdentificationProvider(provider: PlantIdentificationProvider): void {
  activeProvider = provider;
}

export function getPlantIdentificationProvider(): PlantIdentificationProvider {
  return activeProvider;
}

export async function identifyPlant(
  input: PlantIdentificationInput,
): Promise<PlantIdentificationResult> {
  // Capture once so a test/dev provider swap during an in-flight scan cannot make
  // the log and invocation refer to different providers.
  const provider = activeProvider;
  logDev('[PlantIdentification] provider selected', { provider: provider.name });

  acquireScanPriority();
  try {
    return await provider.identifyPlant(input);
  } finally {
    releaseScanPriority();
  }
}
