import type { IAsuswrtCommand, IAsuswrtCommandResult, IAsuswrtConfig, IAsuswrtEvent, IAsuswrtSnapshot } from './asuswrt.types.js';
import { AsuswrtMapper } from './asuswrt.mapper.js';

type TAsuswrtEventHandler = (eventArg: IAsuswrtEvent) => void;

export class AsuswrtClient {
  private currentSnapshot?: IAsuswrtSnapshot;
  private readonly eventHandlers = new Set<TAsuswrtEventHandler>();

  constructor(private readonly config: IAsuswrtConfig) {}

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

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

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

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

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

  public async sendCommand(commandArg: IAsuswrtCommand): Promise<IAsuswrtCommandResult> {
    this.emit({ type: 'command_mapped', command: commandArg, 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: IAsuswrtCommandResult = {
        success: false,
        error: this.unsupportedCommandMessage(commandArg),
        data: { command: commandArg },
      };
      this.emit({ type: 'command_failed', command: commandArg, 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, data: result, deviceId: commandArg.deviceId, entityId: commandArg.entityId, timestamp: Date.now() });
      return result;
    } catch (errorArg) {
      const result: IAsuswrtCommandResult = { success: false, error: errorArg instanceof Error ? errorArg.message : String(errorArg), data: { command: commandArg } };
      this.emit({ type: 'command_failed', command: commandArg, 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: IAsuswrtSnapshot, sourceArg: IAsuswrtSnapshot['source']): IAsuswrtSnapshot {
    const normalized = AsuswrtMapper.toSnapshot({ ...this.config, snapshot: this.cloneSnapshot(snapshotArg) }, snapshotArg.connected);
    return { ...normalized, source: snapshotArg.source || sourceArg };
  }

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

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

  private unsupportedCommandMessage(commandArg: IAsuswrtCommand): string {
    const protocol = this.config.protocol || commandArg.protocol || 'https';
    if (protocol === 'ssh' || protocol === 'telnet') {
      return 'ASUSWRT SSH/Telnet commands are not faked by this native TypeScript port. Provide commandExecutor or nativeClient.executeCommand for live reboot or connected-device actions.';
    }
    return 'ASUSWRT live commands require an injected commandExecutor or nativeClient.executeCommand; snapshot/manual mode only maps commands safely.';
  }

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

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