import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IFrontierSiliconConfig, TFrontierSiliconProtocol } from './frontier_silicon.types.js';
import { frontierSiliconDefaultPin, frontierSiliconDefaultPort, frontierSiliconDefaultTimeoutMs } from './frontier_silicon.types.js';

export class FrontierSiliconConfigFlow implements IConfigFlow<IFrontierSiliconConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IFrontierSiliconConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Frontier Silicon Radio',
      description: 'Configure a local UNDOK/FSAPI endpoint. The default PIN is 1234 unless changed on the device.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'HTTP port', type: 'number' },
        { name: 'pin', label: 'PIN', type: 'password' },
        { name: 'webfsapiUrl', label: 'Web FSAPI URL', type: 'text' },
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'timeoutMs', label: 'Timeout in milliseconds', type: 'number' },
      ],
      submit: async (valuesArg) => {
        const metadata = candidateArg.metadata || {};
        const candidateWebfsapiUrl = this.stringValue(metadata.webfsapiUrl);
        const candidateDeviceUrl = this.stringValue(metadata.deviceUrl) || this.stringValue(metadata.location);
        const webfsapiUrl = this.stringValue(valuesArg.webfsapiUrl) || candidateWebfsapiUrl;
        const endpointUrl = this.parseUrl(webfsapiUrl) || this.parseUrl(candidateDeviceUrl);
        const host = this.stringValue(valuesArg.host) || candidateArg.host || endpointUrl?.hostname;
        if (!host && !webfsapiUrl) {
          return { kind: 'error', title: 'Frontier Silicon setup failed', error: 'A host or Web FSAPI URL is required.' };
        }

        const port = this.numberValue(valuesArg.port) || candidateArg.port || this.urlPort(endpointUrl) || frontierSiliconDefaultPort;
        const protocol = this.protocolValue(metadata.protocol) || this.protocolFromUrl(endpointUrl) || 'http';
        return {
          kind: 'done',
          title: 'Frontier Silicon configured',
          config: {
            host,
            port,
            protocol,
            pin: this.stringValue(valuesArg.pin) || frontierSiliconDefaultPin,
            deviceUrl: candidateDeviceUrl || (host ? this.deviceUrl(protocol, host, port) : undefined),
            webfsapiUrl,
            name: this.stringValue(valuesArg.name) || candidateArg.name,
            uniqueId: candidateArg.id,
            manufacturer: candidateArg.manufacturer,
            model: candidateArg.model,
            timeoutMs: this.numberValue(valuesArg.timeoutMs) || frontierSiliconDefaultTimeoutMs,
          },
        };
      },
    };
  }

  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 value = Number(valueArg);
      return Number.isFinite(value) && value > 0 ? Math.round(value) : undefined;
    }
    return undefined;
  }

  private parseUrl(valueArg: string | undefined): URL | undefined {
    if (!valueArg) {
      return undefined;
    }
    try {
      return new URL(valueArg);
    } catch {
      return undefined;
    }
  }

  private protocolValue(valueArg: unknown): TFrontierSiliconProtocol | undefined {
    return valueArg === 'https' ? 'https' : valueArg === 'http' ? 'http' : undefined;
  }

  private protocolFromUrl(urlArg: URL | undefined): TFrontierSiliconProtocol | undefined {
    return urlArg?.protocol === 'https:' ? 'https' : urlArg?.protocol === 'http:' ? 'http' : undefined;
  }

  private urlPort(urlArg: URL | undefined): number | undefined {
    return urlArg?.port ? Number(urlArg.port) : undefined;
  }

  private deviceUrl(protocolArg: TFrontierSiliconProtocol, hostArg: string, portArg: number): string {
    const includePort = !(protocolArg === 'http' && portArg === 80) && !(protocolArg === 'https' && portArg === 443);
    const host = hostArg.includes(':') && !hostArg.startsWith('[') ? `[${hostArg}]` : hostArg;
    return `${protocolArg}://${host}${includePort ? `:${portArg}` : ''}/device`;
  }
}
