import type * as shxInterfaces from '@smarthome.exchange/interfaces';
import { BaseIntegration } from '../../core/classes.baseintegration.js';
import type { IIntegrationEntity, IIntegrationRuntime, IIntegrationSetupContext, IServiceCallRequest, IServiceCallResult } from '../../core/types.js';
import { FreeboxClient } from './freebox.classes.client.js';
import { FreeboxConfigFlow } from './freebox.classes.configflow.js';
import { createFreeboxDiscoveryDescriptor } from './freebox.discovery.js';
import { FreeboxMapper } from './freebox.mapper.js';
import type { IFreeboxConfig } from './freebox.types.js';
import { freeboxDefaultApiVersion, freeboxDefaultPort, freeboxDisplayName, freeboxDomain, freeboxZeroconfType } from './freebox.types.js';

export class FreeboxIntegration extends BaseIntegration<IFreeboxConfig> {
  public readonly domain = freeboxDomain;
  public readonly displayName = freeboxDisplayName;
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createFreeboxDiscoveryDescriptor();
  public readonly configFlow = new FreeboxConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/freebox',
    upstreamDomain: freeboxDomain,
    integrationType: 'device',
    iotClass: 'local_polling',
    requirements: ['freebox-api==1.3.1'],
    dependencies: ['ffmpeg'],
    afterDependencies: [] as string[],
    codeowners: ['@hacf-fr/reviewers', '@Quentame'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/freebox',
    platforms: ['alarm_control_panel', 'binary_sensor', 'button', 'camera', 'device_tracker', 'sensor', 'switch'],
    zeroconf: [freeboxZeroconfType],
    discovery: {
      zeroconf: freeboxZeroconfType,
      manual: true,
    },
    runtime: {
      type: 'control-runtime',
      polling: `authenticated local Freebox API snapshots, default ${freeboxDefaultApiVersion} on port ${freeboxDefaultPort}`,
      services: ['snapshot', 'status', 'refresh', 'reboot', 'mark_calls_as_read', 'set_wifi_enabled', 'set_home_endpoint_value'],
      controls: 'direct local API only with host plus appToken/sessionToken, or delegated to injected client.execute/commandExecutor',
    },
    localApi: {
      implemented: [
        `mDNS matching for ${freeboxZeroconfType}`,
        'manual host/snapshot/raw-data/injected-client configuration',
        'Freebox app-token session authentication using the documented login challenge/HMAC flow',
        'GET /api_version discovery metadata',
        'authenticated system, connection, call log, storage disk/raid, LAN browser, WiFi config, and Home node snapshots',
        'reboot, mark calls as read, WiFi enable/disable, and Home endpoint value writes when authenticated or delegated',
      ],
      explicitUnsupported: [
        'Freebox cloud/remote APIs outside the local API endpoint',
        'FFmpeg camera streaming proxying inside this package; camera stream URLs are exposed as metadata',
        'pretending controls succeeded without an authenticated host, injected client.execute, or commandExecutor',
      ],
    },
  };

  public async setup(configArg: IFreeboxConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new FreeboxRuntime(new FreeboxClient(configArg));
  }

  public async destroy(): Promise<void> {}
}

export class HomeAssistantFreeboxIntegration extends FreeboxIntegration {}

class FreeboxRuntime implements IIntegrationRuntime {
  public domain = freeboxDomain;

  constructor(private readonly client: FreeboxClient) {}

  public async devices(): Promise<shxInterfaces.data.IDeviceDefinition[]> {
    return FreeboxMapper.toDevices(await this.client.getSnapshot());
  }

  public async entities(): Promise<IIntegrationEntity[]> {
    return FreeboxMapper.toEntities(await this.client.getSnapshot());
  }

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    try {
      if (requestArg.domain === freeboxDomain && (requestArg.service === 'snapshot' || requestArg.service === 'status')) {
        return { success: true, data: await this.client.getSnapshot() };
      }
      if (requestArg.domain === freeboxDomain && requestArg.service === 'refresh') {
        const result = await this.client.refresh();
        return { success: result.success, error: result.error, data: result.snapshot || result.data };
      }

      const snapshot = await this.client.getSnapshot();
      const command = FreeboxMapper.commandForService(snapshot, requestArg);
      if (!command) {
        return { success: false, error: `Unsupported Freebox service or target: ${requestArg.domain}.${requestArg.service}` };
      }
      const data = await this.client.execute(command);
      return { success: true, data: data ?? command };
    } catch (errorArg) {
      return { success: false, error: errorArg instanceof Error ? errorArg.message : String(errorArg) };
    }
  }

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