import * as plugins from '../../plugins.js';
import { SimpleLocalClient, SimpleLocalMapper, type ISimpleLocalSnapshot, type IServiceCallRequest, type IServiceCallResult } from '../../core/index.js';
import { PhilipsJsMapper } from './philips_js.mapper.js';
import type { IPhilipsJsConfig, IPhilipsJsRawApiData, IPhilipsJsSystemInfo, TPhilipsJsRawData } from './philips_js.types.js';
import { philipsJsDefaultApiVersion, philipsJsDefaultHttpPort, philipsJsDefaultHttpsPort, philipsJsDefaultTimeoutMs, philipsJsProfile } from './philips_js.types.js';

export class PhilipsJsClient extends SimpleLocalClient<IPhilipsJsConfig> {
  private cachedSnapshot?: ISimpleLocalSnapshot;
  private currentEndpoint?: IPhilipsJsEndpoint;
  private digestChallenge?: IPhilipsJsDigestChallenge;

  constructor(private readonly clientConfig: IPhilipsJsConfig) {
    super(philipsJsProfile, clientConfig);
  }

  public async getSnapshot(forceRefreshArg = false): Promise<ISimpleLocalSnapshot> {
    if (!forceRefreshArg && this.cachedSnapshot) {
      return SimpleLocalMapper.clone(this.cachedSnapshot);
    }

    if (!forceRefreshArg && this.clientConfig.snapshot) {
      this.cachedSnapshot = PhilipsJsMapper.toSnapshot({ config: this.clientConfig, source: 'snapshot', online: this.clientConfig.snapshot.online });
      return SimpleLocalMapper.clone(this.cachedSnapshot);
    }

    if (this.hasEndpoint() && !this.clientConfig.client && !this.clientConfig.snapshotProvider) {
      try {
        const rawData = await this.fetchRawData();
        this.cachedSnapshot = PhilipsJsMapper.toSnapshot({ config: this.clientConfig, rawData, online: true, source: 'http' });
      } catch (errorArg) {
        this.cachedSnapshot = this.createOfflineSnapshot(errorMessage(errorArg));
      }
      return SimpleLocalMapper.clone(this.cachedSnapshot);
    }

    if (this.clientConfig.client || this.clientConfig.snapshotProvider) {
      this.cachedSnapshot = await super.getSnapshot(forceRefreshArg);
      return SimpleLocalMapper.clone(this.cachedSnapshot);
    }

    if (this.hasManualData()) {
      this.cachedSnapshot = PhilipsJsMapper.toSnapshot({ config: this.clientConfig, rawData: this.rawData(), online: this.clientConfig.online ?? true, source: 'manual' });
      return SimpleLocalMapper.clone(this.cachedSnapshot);
    }

    this.cachedSnapshot = await super.getSnapshot(forceRefreshArg);
    return SimpleLocalMapper.clone(this.cachedSnapshot);
  }

  public async refresh(): Promise<IServiceCallResult> {
    this.cachedSnapshot = undefined;
    const liveCapable = this.hasEndpoint() || Boolean(this.clientConfig.client || this.clientConfig.snapshotProvider);
    const snapshot = await this.getSnapshot(liveCapable);
    const success = liveCapable && snapshot.online && !snapshot.error && snapshot.source !== 'runtime';
    return { success, error: success ? undefined : snapshot.error || 'Philips TV refresh requires a live JointSpace host/url, injected client, or snapshotProvider.', data: snapshot };
  }

  public async execute(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (this.clientConfig.client?.execute || this.clientConfig.commandExecutor || !this.hasEndpoint()) {
      return super.execute(requestArg);
    }

    try {
      const data = requestArg.data || {};
      const result = await this.executeNative(requestArg, data);
      this.cachedSnapshot = undefined;
      return { success: true, data: result };
    } catch (errorArg) {
      return { success: false, error: errorMessage(errorArg) };
    }
  }

  public async destroy(): Promise<void> {
    await this.clientConfig.client?.destroy?.();
  }

  private async fetchRawData(): Promise<IPhilipsJsRawApiData> {
    const system = await this.fetchSystem();
    const endpoint = this.endpointForSystem(system);
    this.currentEndpoint = endpoint;

    const [powerstate, volume, sources, sourceCurrent, channel, activity, applications, application, context, screenstate, ambilightMode, ambilightPower, ambilightCurrentConfiguration, hueLampPower, recordings] = await Promise.all([
      this.getOptional('powerstate', endpoint),
      this.getOptional('audio/volume', endpoint),
      endpoint.apiVersion < 5 ? this.getOptional('sources', endpoint) : Promise.resolve(undefined),
      endpoint.apiVersion < 5 ? this.getOptional('sources/current', endpoint) : Promise.resolve(undefined),
      endpoint.apiVersion >= 5 ? this.getOptional('activities/tv', endpoint) : this.getOptional('channels/current', endpoint),
      endpoint.apiVersion >= 5 ? this.getOptional('activities/current', endpoint) : Promise.resolve(undefined),
      this.jsonFeatureSupported(system, 'applications') ? this.getOptional('applications', endpoint) : Promise.resolve(undefined),
      this.jsonFeatureSupported(system, 'applications') ? this.getOptional('activities/current', endpoint) : Promise.resolve(undefined),
      this.getOptional('context', endpoint),
      endpoint.apiVersion >= 5 ? this.getOptional('screenstate', endpoint) : Promise.resolve(undefined),
      this.getOptional('ambilight/mode', endpoint),
      endpoint.apiVersion >= 5 ? this.getOptional('ambilight/power', endpoint) : Promise.resolve(undefined),
      this.jsonFeatureSupported(system, 'ambilight', 'Ambilight') ? this.getOptional('ambilight/currentconfiguration', endpoint) : Promise.resolve(undefined),
      this.jsonFeatureSupported(system, 'ambilight', 'Hue') ? this.getOptional('HueLamp/power', endpoint) : Promise.resolve(undefined),
      endpoint.apiVersion === 6 && this.jsonFeatureSupported(system, 'recordings', 'List') ? this.getOptional('recordings/list', endpoint) : Promise.resolve(undefined),
    ]);

    return {
      system,
      powerstate,
      volume,
      sources,
      sourceCurrent,
      channel,
      activity,
      applications,
      application,
      context,
      screenstate,
      ambilightMode,
      ambilightPower,
      ambilightCurrentConfiguration,
      hueLampPower,
      recordings,
      apiVersion: endpoint.apiVersion,
      protocol: endpoint.protocol,
      fetchedAt: new Date().toISOString(),
    };
  }

  private async executeNative(requestArg: IServiceCallRequest, dataArg: Record<string, unknown>): Promise<unknown> {
    const endpoint = this.currentEndpoint || await this.ensureEndpoint();
    const domain = requestArg.domain;
    const service = requestArg.service;

    if (service === 'press' || service === 'send_command') {
      const commands = commandList(dataArg.command ?? dataArg.commands ?? dataArg.key ?? dataArg.keys);
      if (!commands.length) {
        throw new Error('Philips TV send_command/press requires data.command, data.commands, data.key, or data.keys.');
      }
      const responses: unknown[] = [];
      for (const command of commands) {
        responses.push(await this.postJson('input/key', { key: command }, endpoint));
      }
      return responses;
    }

    if (domain === 'light' && (service === 'turn_on' || service === 'turn_off' || service === 'toggle')) {
      const power = service === 'turn_off' ? 'Off' : 'On';
      return endpoint.apiVersion >= 5
        ? this.postJson('ambilight/power', { power }, endpoint)
        : this.postJson('ambilight/mode', { current: power === 'On' ? 'internal' : 'manual' }, endpoint);
    }

    if (domain === 'switch' && stringValue(dataArg.switch) === 'screen_state') {
      return this.postJson('screenstate', { screenstate: service === 'turn_off' ? 'Off' : 'On' }, endpoint);
    }

    if (domain === 'switch' && stringValue(dataArg.switch) === 'ambilight_hue') {
      return this.postJson('HueLamp/power', { power: service === 'turn_off' ? 'Off' : 'On' }, endpoint);
    }

    if (service === 'turn_off') {
      return this.postJson('input/key', { key: 'Standby' }, endpoint);
    }
    if (service === 'turn_on') {
      return this.postJson('powerstate', { powerstate: 'On' }, endpoint);
    }
    if (service === 'media_play') {
      return this.postJson('input/key', { key: 'Play' }, endpoint);
    }
    if (service === 'media_pause') {
      return this.postJson('input/key', { key: 'Pause' }, endpoint);
    }
    if (service === 'media_play_pause') {
      return this.postJson('input/key', { key: 'PlayPause' }, endpoint);
    }
    if (service === 'media_stop') {
      return this.postJson('input/key', { key: 'Stop' }, endpoint);
    }
    if (service === 'volume_up') {
      return this.postJson('input/key', { key: 'VolumeUp' }, endpoint);
    }
    if (service === 'volume_down') {
      return this.postJson('input/key', { key: 'VolumeDown' }, endpoint);
    }
    if (service === 'volume_mute') {
      const mute = boolValue(dataArg.mute ?? dataArg.is_volume_muted);
      return mute === undefined ? this.postJson('input/key', { key: 'Mute' }, endpoint) : this.postJson('audio/volume', { muted: mute }, endpoint);
    }
    if (service === 'volume_set' || service === 'set_volume_level' || service === 'set_level') {
      const level = numberValue(dataArg.volume_level ?? dataArg.volume ?? dataArg.level ?? dataArg.percentage);
      if (level === undefined) {
        throw new Error('Philips TV volume_set requires data.volume_level, data.volume, data.level, or data.percentage.');
      }
      const volume = await this.getOptional('audio/volume', endpoint) || {};
      const max = numberValue(volume.max) || 100;
      const current = level <= 1 ? Math.round(level * max) : Math.round(level);
      return this.postJson('audio/volume', { current: Math.max(0, Math.min(max, current)), muted: boolValue(volume.muted) ?? false }, endpoint);
    }
    if (service === 'select_source') {
      const source = stringValue(dataArg.source ?? dataArg.source_id ?? dataArg.sourceId);
      const intent = objectValue(dataArg.intent);
      if (endpoint.apiVersion < 5) {
        if (!source) {
          throw new Error('Philips TV select_source requires data.source for API v1.');
        }
        return this.postJson('sources/current', { id: source }, endpoint);
      }
      if (intent) {
        return this.postJson('activities/launch', { intent }, endpoint);
      }
      if (!source) {
        throw new Error('Philips TV select_source on API v5/v6 requires data.intent or data.source with a content:// URI.');
      }
      return this.postJson('activities/launch', { intent: sourceIntent(source) }, endpoint);
    }

    throw new Error(`Unsupported Philips TV service: ${requestArg.domain}.${requestArg.service}`);
  }

  private async fetchSystem(): Promise<IPhilipsJsSystemInfo> {
    const candidates = this.endpointCandidates();
    let lastError: unknown;
    for (const endpoint of candidates) {
      try {
        const system = await this.getJson('system', endpoint, false) as IPhilipsJsSystemInfo | undefined;
        if (system && Object.keys(system).length) {
          this.currentEndpoint = { ...endpoint, apiVersion: numberValue(system.api_version?.Major) || endpoint.apiVersion };
          return decodeSystem(system);
        }
      } catch (errorArg) {
        lastError = errorArg;
      }
    }
    throw new Error(`Philips TV JointSpace /system request failed: ${lastError ? errorMessage(lastError) : 'no response'}`);
  }

  private endpointForSystem(systemArg: IPhilipsJsSystemInfo): IPhilipsJsEndpoint {
    const base = this.currentEndpoint || this.endpointCandidates()[0];
    const apiVersion = numberValue(systemArg.api_version?.Major) || base.apiVersion;
    const secured = securedTransport(systemArg);
    if (secured && !base.explicitUrl && base.protocol !== 'https') {
      return {
        ...base,
        protocol: 'https',
        port: base.explicitPort ? base.port : philipsJsDefaultHttpsPort,
        apiVersion,
      };
    }
    return { ...base, apiVersion };
  }

  private async ensureEndpoint(): Promise<IPhilipsJsEndpoint> {
    if (this.currentEndpoint) {
      return this.currentEndpoint;
    }
    const system = await this.fetchSystem();
    this.currentEndpoint = this.endpointForSystem(system);
    return this.currentEndpoint;
  }

  private async getOptional(pathArg: string, endpointArg: IPhilipsJsEndpoint): Promise<Record<string, unknown> | undefined> {
    return await this.getJson(pathArg, endpointArg, true) as Record<string, unknown> | undefined;
  }

  private async getJson(pathArg: string, endpointArg: IPhilipsJsEndpoint, optionalArg: boolean): Promise<unknown> {
    return this.requestJson('GET', pathArg, undefined, endpointArg, optionalArg);
  }

  private async postJson(pathArg: string, bodyArg: Record<string, unknown>, endpointArg: IPhilipsJsEndpoint): Promise<unknown> {
    const result = await this.requestJson('POST', pathArg, bodyArg, endpointArg, false);
    return result ?? {};
  }

  private async requestJson(methodArg: 'GET' | 'POST', pathArg: string, bodyArg: Record<string, unknown> | undefined, endpointArg: IPhilipsJsEndpoint, optionalArg: boolean): Promise<unknown> {
    const url = endpointUrl(endpointArg, pathArg);
    const response = await this.fetchWithAuth(methodArg, url, bodyArg);
    const text = await response.text();
    if (response.status === 401) {
      throw new Error('Philips TV JointSpace authentication failed; provide previously paired username/password for digest-auth TVs.');
    }
    if (!response.ok) {
      if (optionalArg && response.status === 404) {
        return undefined;
      }
      throw new Error(`Philips TV JointSpace ${methodArg} ${pathArg} failed with ${response.status}: ${text.slice(0, 160)}`);
    }
    return parsePhilipsJson(text);
  }

  private async fetchWithAuth(methodArg: 'GET' | 'POST', urlArg: string, bodyArg?: Record<string, unknown>): Promise<Response> {
    const initial = await this.fetchOnce(methodArg, urlArg, bodyArg, this.digestChallenge ? this.digestAuthorization(methodArg, urlArg, this.digestChallenge) : undefined);
    if (initial.status !== 401 || !this.clientConfig.username) {
      return initial;
    }
    const challenge = parseDigestChallenge(initial.headers.get('www-authenticate'));
    if (!challenge) {
      return initial;
    }
    this.digestChallenge = challenge;
    return this.fetchOnce(methodArg, urlArg, bodyArg, this.digestAuthorization(methodArg, urlArg, challenge));
  }

  private async fetchOnce(methodArg: 'GET' | 'POST', urlArg: string, bodyArg?: Record<string, unknown>, authorizationArg?: string): Promise<Response> {
    const timeoutMs = this.clientConfig.timeoutMs || philipsJsDefaultTimeoutMs;
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), timeoutMs);
    try {
      const headers: Record<string, string> = { accept: 'application/json' };
      if (authorizationArg) {
        headers.authorization = authorizationArg;
      }
      if (bodyArg !== undefined) {
        headers['content-type'] = 'application/json';
      }
      return await globalThis.fetch(urlArg, { method: methodArg, headers, body: bodyArg === undefined ? undefined : JSON.stringify(bodyArg), signal: controller.signal });
    } finally {
      clearTimeout(timer);
    }
  }

  private digestAuthorization(methodArg: string, urlArg: string, challengeArg: IPhilipsJsDigestChallenge): string {
    const username = this.clientConfig.username || '';
    const password = this.clientConfig.password || '';
    const url = new URL(urlArg);
    const uri = `${url.pathname}${url.search}`;
    const algorithm = challengeArg.algorithm || 'MD5';
    const hashName = digestHashName(algorithm);
    const qop = challengeArg.qop?.split(',').map((itemArg) => itemArg.trim()).includes('auth') ? 'auth' : undefined;
    const nc = '00000001';
    const cnonce = plugins.crypto.randomBytes(8).toString('hex');
    let ha1 = digest(hashName, `${username}:${challengeArg.realm}:${password}`);
    if (algorithm.toLowerCase().endsWith('-sess')) {
      ha1 = digest(hashName, `${ha1}:${challengeArg.nonce}:${cnonce}`);
    }
    const ha2 = digest(hashName, `${methodArg}:${uri}`);
    const response = qop
      ? digest(hashName, `${ha1}:${challengeArg.nonce}:${nc}:${cnonce}:${qop}:${ha2}`)
      : digest(hashName, `${ha1}:${challengeArg.nonce}:${ha2}`);
    const parts = [
      `username=${quoteDigest(username)}`,
      `realm=${quoteDigest(challengeArg.realm)}`,
      `nonce=${quoteDigest(challengeArg.nonce)}`,
      `uri=${quoteDigest(uri)}`,
      `response=${quoteDigest(response)}`,
      `algorithm=${algorithm}`,
    ];
    if (challengeArg.opaque) {
      parts.push(`opaque=${quoteDigest(challengeArg.opaque)}`);
    }
    if (qop) {
      parts.push(`qop=${qop}`, `nc=${nc}`, `cnonce=${quoteDigest(cnonce)}`);
    }
    return `Digest ${parts.join(', ')}`;
  }

  private jsonFeatureSupported(systemArg: IPhilipsJsSystemInfo, typeArg: string, valueArg?: string): boolean {
    const features = systemArg.featuring?.jsonfeatures?.[typeArg];
    if (!Array.isArray(features)) {
      return false;
    }
    return valueArg ? features.includes(valueArg) : features.length > 0;
  }

  private endpointCandidates(): IPhilipsJsEndpoint[] {
    const endpoint = this.endpoint();
    if (!endpoint) {
      return [];
    }
    if (endpoint.explicitUrl) {
      return [endpoint];
    }
    const alternate: IPhilipsJsEndpoint = {
      ...endpoint,
      protocol: endpoint.protocol === 'https' ? 'http' : 'https',
      port: endpoint.explicitPort ? endpoint.port : endpoint.protocol === 'https' ? philipsJsDefaultHttpPort : philipsJsDefaultHttpsPort,
    };
    return [endpoint, alternate];
  }

  private endpoint(): IPhilipsJsEndpoint | undefined {
    const rawUrl = stringValue(this.clientConfig.url) || (typeof this.clientConfig.host === 'string' && this.clientConfig.host.includes('://') ? this.clientConfig.host : undefined);
    if (rawUrl) {
      const parsed = parseUrl(rawUrl);
      if (!parsed) {
        return undefined;
      }
      const protocol = parsed.protocol === 'https:' ? 'https' : 'http';
      return {
        host: parsed.hostname,
        port: this.clientConfig.port || numberValue(parsed.port) || (protocol === 'https' ? philipsJsDefaultHttpsPort : philipsJsDefaultHttpPort),
        protocol,
        apiVersion: this.clientConfig.apiVersion || apiVersionFromPath(parsed.pathname) || philipsJsDefaultApiVersion,
        explicitUrl: true,
        explicitPort: Boolean(this.clientConfig.port || parsed.port),
      };
    }

    const host = stringValue(this.clientConfig.host);
    if (!host) {
      return undefined;
    }
    const protocol = this.clientConfig.useTls ? 'https' : 'http';
    return {
      host,
      port: this.clientConfig.port || (protocol === 'https' ? philipsJsDefaultHttpsPort : philipsJsDefaultHttpPort),
      protocol,
      apiVersion: this.clientConfig.apiVersion || philipsJsDefaultApiVersion,
      explicitUrl: false,
      explicitPort: Boolean(this.clientConfig.port),
    };
  }

  private hasEndpoint(): boolean {
    return Boolean(this.endpoint());
  }

  private hasManualData(): boolean {
    return this.rawData() !== undefined || Boolean(this.clientConfig.entities?.length || this.clientConfig.snapshot);
  }

  private rawData(): TPhilipsJsRawData | undefined {
    return this.clientConfig.rawData as TPhilipsJsRawData | undefined ?? this.clientConfig.rawText;
  }

  private createOfflineSnapshot(errorArg: string): ISimpleLocalSnapshot {
    return PhilipsJsMapper.toSnapshot({ config: this.clientConfig, online: false, source: 'runtime', error: errorArg });
  }
}

interface IPhilipsJsEndpoint {
  host: string;
  port: number;
  protocol: 'http' | 'https';
  apiVersion: number;
  explicitUrl: boolean;
  explicitPort: boolean;
}

interface IPhilipsJsDigestChallenge {
  realm: string;
  nonce: string;
  qop?: string;
  opaque?: string;
  algorithm?: string;
}

const philipsAuthSharedKey = Buffer.from('ZmVay1EQVFOaZhwQ4Kv81ypLAZNczV9sG4KkseXWn1NEk6cXmPKO/MCa9sryslvLCFMnNe4Z4CPXzToowvhHvA==', 'base64');

const endpointUrl = (endpointArg: IPhilipsJsEndpoint, pathArg: string): string => `${endpointArg.protocol}://${endpointArg.host}:${endpointArg.port}/${endpointArg.apiVersion}/${pathArg.replace(/^\/+/, '')}`;

const decodeSystem = (systemArg: IPhilipsJsSystemInfo): IPhilipsJsSystemInfo => {
  const decoded: Record<string, unknown> = {};
  for (const [key, value] of Object.entries(systemArg)) {
    if (key.endsWith('_encrypted') && typeof value === 'string') {
      decoded[key.slice(0, -10)] = decryptPhilipsField(value);
    } else {
      decoded[key] = value;
    }
  }
  return decoded as IPhilipsJsSystemInfo;
};

const decryptPhilipsField = (valueArg: string): string => {
  if (!valueArg.trim()) {
    return '';
  }
  const raw = Buffer.from(valueArg.trim(), 'base64');
  if (raw.length < 17) {
    return '';
  }
  const decipher = plugins.crypto.createDecipheriv('aes-128-cbc', philipsAuthSharedKey.subarray(0, 16), raw.subarray(0, 16));
  return Buffer.concat([decipher.update(raw.subarray(16)), decipher.final()]).toString('utf8');
};

const securedTransport = (systemArg: IPhilipsJsSystemInfo): boolean => {
  const value = systemArg.featuring?.systemfeatures?.secured_transport;
  return value === true || value === 'true';
};

const parsePhilipsJson = (textArg: string): unknown => {
  const text = textArg.trim();
  if (!text || text === 'Context Service not started' || text === '}') {
    return {};
  }
  try {
    return JSON.parse(text) as Record<string, unknown>;
  } catch {
    const adjusted = text.replace('"channelList": { "id": "version", "" }', '"channelList": { "id": "all", "version": "" }').replace('{,', '{').replace(',}', '}').replace(/,,+/g, ',');
    return JSON.parse(adjusted) as Record<string, unknown>;
  }
};

const sourceIntent = (sourceArg: string): Record<string, unknown> => ({
  extras: { uri: sourceArg },
  action: 'org.droidtv.playtv.SELECTURI',
  component: {
    packageName: 'org.droidtv.playtv',
    className: 'org.droidtv.playtv.PlayTvActivity',
  },
});

const commandList = (valueArg: unknown): string[] => {
  if (Array.isArray(valueArg)) {
    return valueArg.map((itemArg) => stringValue(itemArg)).filter((itemArg): itemArg is string => Boolean(itemArg));
  }
  const single = stringValue(valueArg);
  return single ? [single] : [];
};

const parseDigestChallenge = (headerArg: string | null): IPhilipsJsDigestChallenge | undefined => {
  if (!headerArg || !headerArg.toLowerCase().startsWith('digest ')) {
    return undefined;
  }
  const params: Record<string, string> = {};
  const pattern = /(\w+)=('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|[^,]+)/g;
  let match: RegExpExecArray | null;
  while ((match = pattern.exec(headerArg.slice(7))) !== null) {
    params[match[1]] = unquoteDigest(match[2].trim());
  }
  if (!params.realm || !params.nonce) {
    return undefined;
  }
  return { realm: params.realm, nonce: params.nonce, qop: params.qop, opaque: params.opaque, algorithm: params.algorithm };
};

const digestHashName = (algorithmArg: string): string => {
  const normalized = algorithmArg.toLowerCase();
  if (normalized.startsWith('sha-256')) {
    return 'sha256';
  }
  if (normalized.startsWith('sha-512')) {
    return 'sha512';
  }
  if (normalized.startsWith('sha')) {
    return 'sha1';
  }
  return 'md5';
};

const digest = (hashNameArg: string, valueArg: string): string => plugins.crypto.createHash(hashNameArg).update(valueArg).digest('hex');

const quoteDigest = (valueArg: string): string => `"${valueArg.replace(/(["\\])/g, '\\$1')}"`;

const unquoteDigest = (valueArg: string): string => valueArg.startsWith('"') && valueArg.endsWith('"') ? valueArg.slice(1, -1).replace(/\\(["\\])/g, '$1') : valueArg.startsWith("'") && valueArg.endsWith("'") ? valueArg.slice(1, -1).replace(/\\(['\\])/g, '$1') : valueArg;

const parseUrl = (valueArg: string): URL | undefined => {
  try {
    return new URL(valueArg.includes('://') ? valueArg : `http://${valueArg}`);
  } catch {
    return undefined;
  }
};

const apiVersionFromPath = (pathArg: string): number | undefined => {
  const segment = pathArg.split('/').filter(Boolean)[0];
  return numberValue(segment);
};

const objectValue = (valueArg: unknown): Record<string, unknown> | undefined => {
  return valueArg && typeof valueArg === 'object' && !Array.isArray(valueArg) ? valueArg as Record<string, unknown> : undefined;
};

const stringValue = (valueArg: unknown): string | undefined => {
  if (typeof valueArg === 'number' && Number.isFinite(valueArg)) {
    return String(valueArg);
  }
  return 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.trim());
    return Number.isFinite(parsed) ? parsed : undefined;
  }
  return undefined;
};

const boolValue = (valueArg: unknown): boolean | undefined => {
  if (typeof valueArg === 'boolean') {
    return valueArg;
  }
  if (typeof valueArg === 'string') {
    if (valueArg.toLowerCase() === 'true') {
      return true;
    }
    if (valueArg.toLowerCase() === 'false') {
      return false;
    }
  }
  return undefined;
};

const errorMessage = (errorArg: unknown): string => errorArg instanceof Error ? errorArg.message : String(errorArg);
