import { DevoloHomeNetworkMapper } from './devolo_home_network.mapper.js';
import type {
  IDevoloCommand,
  IDevoloCommandResult,
  IDevoloConfig,
  IDevoloEvent,
  IDevoloSnapshot,
} from './devolo_home_network.types.js';

type TDevoloEventHandler = (eventArg: IDevoloEvent) => void;

export class DevoloHomeNetworkClient {
  private currentSnapshot?: IDevoloSnapshot;
  private readonly eventHandlers = new Set<TDevoloEventHandler>();

  constructor(private readonly config: IDevoloConfig) {}

  public async getSnapshot(): Promise<IDevoloSnapshot> {
    if (this.config.nativeClient?.getSnapshot) {
      this.currentSnapshot = this.normalizeSnapshot(await this.config.nativeClient.getSnapshot(), 'provider');
      return this.cloneSnapshot(this.currentSnapshot);
    }

    if (this.config.snapshotProvider) {
      const snapshot = await this.config.snapshotProvider();
      if (snapshot) {
        this.currentSnapshot = this.normalizeSnapshot(snapshot, 'provider');
        return this.cloneSnapshot(this.currentSnapshot);
      }
    }

    if (!this.currentSnapshot) {
      this.currentSnapshot = DevoloHomeNetworkMapper.toSnapshot(this.config);
    }
    return this.cloneSnapshot(this.currentSnapshot);
  }

  public onEvent(handlerArg: TDevoloEventHandler): () => void {
    this.eventHandlers.add(handlerArg);
    return () => this.eventHandlers.delete(handlerArg);
  }

  public async refresh(): Promise<IDevoloCommandResult> {
    try {
      this.currentSnapshot = undefined;
      const snapshot = await this.getSnapshot();
      this.emit({ type: 'snapshot_refreshed', data: snapshot, timestamp: Date.now() });
      return { success: true, data: snapshot };
    } catch (errorArg) {
      const error = errorArg instanceof Error ? errorArg.message : String(errorArg);
      const snapshot = DevoloHomeNetworkMapper.toSnapshot({ ...this.config, snapshot: this.currentSnapshot }, false);
      this.currentSnapshot = snapshot;
      this.emit({ type: 'refresh_failed', error, data: snapshot, timestamp: Date.now() });
      return { success: false, error, data: snapshot };
    }
  }

  public async sendCommand(commandArg: IDevoloCommand): Promise<IDevoloCommandResult> {
    this.emit({ type: 'command_mapped', command: commandArg, action: commandArg.action, deviceId: commandArg.deviceId, entityId: commandArg.entityId, timestamp: Date.now() });

    const executor = this.config.commandExecutor || this.config.nativeClient?.executeCommand?.bind(this.config.nativeClient);
    if (!executor) {
      const result: IDevoloCommandResult = {
        success: false,
        error: 'devolo Home Network live device commands are not faked by this native TypeScript port. Provide commandExecutor or nativeClient.executeCommand for LED, guest Wi-Fi, WPS, restart, pairing, identify, or firmware update actions.',
        data: { command: commandArg },
      };
      this.emit({ type: 'command_failed', command: commandArg, action: commandArg.action, data: result, deviceId: commandArg.deviceId, entityId: commandArg.entityId, timestamp: Date.now() });
      return result;
    }

    try {
      const result = this.commandResult(await executor(commandArg), commandArg);
      this.emit({ type: result.success ? 'command_executed' : 'command_failed', command: commandArg, action: commandArg.action, data: result, deviceId: commandArg.deviceId, entityId: commandArg.entityId, timestamp: Date.now() });
      return result;
    } catch (errorArg) {
      const result: IDevoloCommandResult = { success: false, error: errorArg instanceof Error ? errorArg.message : String(errorArg), data: { command: commandArg } };
      this.emit({ type: 'command_failed', command: commandArg, action: commandArg.action, data: result, deviceId: commandArg.deviceId, entityId: commandArg.entityId, timestamp: Date.now() });
      return result;
    }
  }

  public async destroy(): Promise<void> {
    await this.config.nativeClient?.destroy?.();
    this.eventHandlers.clear();
  }

  private normalizeSnapshot(snapshotArg: IDevoloSnapshot, sourceArg: IDevoloSnapshot['source']): IDevoloSnapshot {
    const normalized = DevoloHomeNetworkMapper.toSnapshot({ ...this.config, snapshot: this.cloneSnapshot(snapshotArg) }, snapshotArg.connected);
    return { ...normalized, source: snapshotArg.source || sourceArg };
  }

  private commandResult(resultArg: unknown, commandArg: IDevoloCommand): IDevoloCommandResult {
    if (this.isCommandResult(resultArg)) {
      return resultArg;
    }
    return { success: true, data: resultArg ?? { command: commandArg } };
  }

  private isCommandResult(valueArg: unknown): valueArg is IDevoloCommandResult {
    return Boolean(valueArg && typeof valueArg === 'object' && 'success' in valueArg);
  }

  private emit(eventArg: IDevoloEvent): void {
    for (const handler of this.eventHandlers) {
      handler(eventArg);
    }
  }

  private cloneSnapshot<TSnapshot extends IDevoloSnapshot>(snapshotArg: TSnapshot): TSnapshot {
    return JSON.parse(JSON.stringify(snapshotArg)) as TSnapshot;
  }
}

export const DevoloClient = DevoloHomeNetworkClient;
