// DaVoiceTTSBridge.m
#import "DaVoiceTTSBridge.h"
#import <React/RCTLog.h>

@interface DaVoiceTTSBridge()

@property (nonatomic, strong) DaVoiceTTS *ttsInstance;

@end

@implementation DaVoiceTTSBridge

RCT_EXPORT_MODULE();

+ (BOOL)requiresMainQueueSetup {
    RCTLogInfo(@"[DaVoiceTTSBridge] requiresMainQueueSetup called (module loaded).");
  NSLog(@"[DaVoiceTTSBridge] requiresMainQueueSetup called (module loaded).");

  return YES;
}

- (instancetype)init {
  self = [super init];
  if (self) {
    RCTLogInfo(@"[DaVoiceTTSBridge] init called.");
    NSLog(@"[DaVoiceTTSBridge] init called.");
  }
  return self;
}

// Declare events if needed (empty if none)
- (NSArray<NSString *> *)supportedEvents {
  RCTLogInfo(@"[DaVoiceTTSBridge] supportedEvents called.");
  NSLog(@"[DaVoiceTTSBridge] supportedEvents called.");
  return @[]; // If you don't have events, leave empty.
}

RCT_EXPORT_METHOD(initTTS:(NSDictionary *)configDict
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
  RCTLogInfo(@"[DaVoiceTTSBridge] initTTS called with configDict: %@", configDict);
  NSLog(@"[DaVoiceTTSBridge] initTTS called with configDict: %@", configDict);
  NSString *modelPath = configDict[@"model"];

  if (!modelPath) {
    reject(@"invalid_config", @"Missing required 'model' key", nil);
    return;
  }

  NSURL *modelURL = [NSURL fileURLWithPath:modelPath];

  NSError *error = nil;
  self.ttsInstance = [[DaVoiceTTS alloc] initWithModel:modelURL error:&error];

  if (error || !self.ttsInstance) {
    reject(@"init_failed", error.localizedDescription ?: @"Failed to initialize", error);
  } else {
    resolve(@"TTS initialized");
  }
}

RCT_EXPORT_METHOD(speak:(NSString *)text
                  speakerId:(nonnull NSNumber *)speakerId
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
  if (!self.ttsInstance) {
    reject(@"no_instance", @"TTS not initialized", nil);
    return;
  }

  [self.ttsInstance speak:text sid:[speakerId intValue]];
  resolve(@"Speaking");
}

@end
