import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IOpenthermGwConfig } from './opentherm_gw.types.js';
import { openthermGwDefaultTcpPort } from './opentherm_gw.types.js';

export class OpenthermGwConfigFlow implements IConfigFlow<IOpenthermGwConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IOpenthermGwConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect OpenTherm Gateway',
      description: 'Use a raw TCP serial bridge host/port, or provide a serial path for metadata-only setup.',
      fields: [
        { name: 'name', label: 'Name', type: 'text', required: true },
        { name: 'host', label: 'TCP host', type: 'text' },
        { name: 'port', label: 'TCP port', type: 'number' },
        { name: 'device', label: 'Serial path or URL', type: 'text' },
        { name: 'timeoutMs', label: 'Timeout in milliseconds', type: 'number' },
      ],
      submit: async (valuesArg) => {
        const host = stringValue(valuesArg.host) || candidateArg.host;
        const device = stringValue(valuesArg.device) || stringValue(candidateArg.metadata?.device);
        if (!host && !device) {
          return { kind: 'error', title: 'OpenTherm Gateway endpoint missing', error: 'Provide a TCP host or serial path.' };
        }
        return {
          kind: 'done',
          title: 'OpenTherm Gateway configured',
          config: {
            id: stringValue(candidateArg.id) || (host ? `${host}:${numberValue(valuesArg.port) || candidateArg.port || openthermGwDefaultTcpPort}` : device),
            name: stringValue(valuesArg.name) || candidateArg.name || 'OpenTherm Gateway',
            host,
            port: numberValue(valuesArg.port) || candidateArg.port || (host ? openthermGwDefaultTcpPort : undefined),
            device,
            timeoutMs: numberValue(valuesArg.timeoutMs),
          },
        };
      },
    };
  }
}

const stringValue = (valueArg: unknown): string | undefined => typeof valueArg === 'string' && valueArg.trim() ? valueArg.trim() : undefined;

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