import type { IFritzCommand, IFritzCommandResult, IFritzConfig, IFritzEvent, IFritzSnapshot } from './fritz.types.js';
import { FritzMapper } from './fritz.mapper.js';

type TFritzEventHandler = (eventArg: IFritzEvent) => void;

export class FritzClient {
  private currentSnapshot?: IFritzSnapshot;
  private readonly eventHandlers = new Set<TFritzEventHandler>();

  constructor(private readonly config: IFritzConfig) {}

  public async getSnapshot(): Promise<IFritzSnapshot> {
    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 = FritzMapper.toSnapshot(this.config);
    }
    return this.cloneSnapshot(this.currentSnapshot);
  }

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

  public async refresh(): Promise<IFritzCommandResult> {
    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 = FritzMapper.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: IFritzCommand): Promise<IFritzCommandResult> {
    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: IFritzCommandResult = {
        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: IFritzCommandResult = { 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: IFritzSnapshot, sourceArg: IFritzSnapshot['source']): IFritzSnapshot {
    const normalized = FritzMapper.toSnapshot({ ...this.config, snapshot: this.cloneSnapshot(snapshotArg) }, snapshotArg.connected);
    return { ...normalized, source: snapshotArg.source || sourceArg };
  }

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

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

  private unsupportedCommandMessage(commandArg: IFritzCommand): string {
    const action = commandArg.action.replace(/_/g, ' ');
    return `FRITZ!Box live TR-064/HTTP ${action} commands are not faked by this native TypeScript port. Provide commandExecutor or nativeClient.executeCommand for live router, switch, client, or service actions.`;
  }

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

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