import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IChannelsConfig, IChannelsFavoriteChannel, IChannelsSnapshot, IChannelsStatus } from './channels.types.js';
import { channelsDefaultPort } from './channels.types.js';

const defaultTimeoutMs = 1000;

export class ChannelsConfigFlow implements IConfigFlow<IChannelsConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IChannelsConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Channels',
      description: 'Configure the local Channels HTTP API endpoint.',
      fields: [
        { name: 'host', label: 'Host', type: 'text' },
        { name: 'port', label: 'Port', type: 'number' },
        { name: 'name', label: 'Name', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const metadataEndpoint = endpointFromUrl(this.stringValue(candidateArg.metadata?.url));
        const valueEndpoint = endpointFromUrl(this.stringValue(valuesArg.host));
        const host = valueEndpoint.host || this.stringValue(valuesArg.host) || candidateArg.host || metadataEndpoint.host;
        const port = this.numberValue(valuesArg.port) || valueEndpoint.port || candidateArg.port || metadataEndpoint.port || channelsDefaultPort;
        const name = this.stringValue(valuesArg.name) || candidateArg.name || 'Channels';
        const snapshot = this.snapshotValue(candidateArg.metadata?.snapshot);
        const status = this.statusValue(candidateArg.metadata?.status);
        const favoriteChannels = this.favoriteChannelsValue(candidateArg.metadata?.favoriteChannels);
        if (!host && !snapshot && !status) {
          return { kind: 'error', title: 'Channels setup failed', error: 'Channels setup requires a host or snapshot data.' };
        }
        return {
          kind: 'done',
          title: 'Channels configured',
          config: {
            host,
            port,
            name,
            uniqueId: candidateArg.id,
            timeoutMs: defaultTimeoutMs,
            snapshot,
            status,
            favoriteChannels,
          },
        };
      },
    };
  }

  private stringValue(valueArg: unknown): string | undefined {
    return typeof valueArg === 'string' && valueArg.trim() ? valueArg.trim() : undefined;
  }

  private numberValue(valueArg: unknown): number | undefined {
    if (typeof valueArg === 'number' && Number.isFinite(valueArg) && valueArg > 0) {
      return Math.round(valueArg);
    }
    if (typeof valueArg === 'string' && valueArg.trim()) {
      const parsed = Number(valueArg);
      return Number.isFinite(parsed) && parsed > 0 ? Math.round(parsed) : undefined;
    }
    return undefined;
  }

  private snapshotValue(valueArg: unknown): IChannelsSnapshot | undefined {
    return valueArg && typeof valueArg === 'object' ? valueArg as IChannelsSnapshot : undefined;
  }

  private statusValue(valueArg: unknown): IChannelsStatus | undefined {
    return valueArg && typeof valueArg === 'object' ? valueArg as IChannelsStatus : undefined;
  }

  private favoriteChannelsValue(valueArg: unknown): IChannelsFavoriteChannel[] | undefined {
    return Array.isArray(valueArg) ? valueArg as IChannelsFavoriteChannel[] : undefined;
  }
}

const endpointFromUrl = (valueArg: string | undefined): { host?: string; port?: number } => {
  if (!valueArg) {
    return {};
  }
  const value = /^https?:\/\//i.test(valueArg) ? valueArg : `http://${valueArg}`;
  try {
    const url = new URL(value);
    return {
      host: url.hostname,
      port: url.port ? Number(url.port) : undefined,
    };
  } catch {
    return {};
  }
};
