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 { FroniusClient } from './fronius.classes.client.js';
import { FroniusConfigFlow } from './fronius.classes.configflow.js';
import { createFroniusDiscoveryDescriptor } from './fronius.discovery.js';
import { FroniusMapper } from './fronius.mapper.js';
import type { IFroniusConfig } from './fronius.types.js';
import { froniusDefaultHttpPort, froniusDhcpMacPrefix, froniusDisplayName, froniusDomain } from './fronius.types.js';

export class FroniusIntegration extends BaseIntegration<IFroniusConfig> {
  public readonly domain = froniusDomain;
  public readonly displayName = froniusDisplayName;
  public readonly status = 'read-only-runtime' as const;
  public readonly discoveryDescriptor = createFroniusDiscoveryDescriptor();
  public readonly configFlow = new FroniusConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/fronius',
    upstreamDomain: froniusDomain,
    integrationType: 'hub',
    iotClass: 'local_polling',
    qualityScale: 'platinum',
    requirements: ['PyFronius==0.8.2'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@farmio'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/fronius',
    platforms: ['sensor'],
    dhcp: [{ macaddress: `${froniusDhcpMacPrefix}*` }],
    discovery: {
      dhcp: `MAC prefix ${froniusDhcpMacPrefix}* from the Home Assistant manifest`,
      manual: true,
    },
    runtime: {
      type: 'read-only-runtime',
      polling: 'local Fronius Solar API snapshots over HTTP/HTTPS',
      services: ['snapshot', 'status', 'refresh'],
      controls: 'delegated only to an injected client.execute or commandExecutor',
    },
    localApi: {
      implemented: [
        `DHCP matching for Fronius MAC prefix ${froniusDhcpMacPrefix}*`,
        'manual host/snapshot/raw-data/injected-client configuration',
        `GET http://host:${froniusDefaultHttpPort}/solar_api/GetAPIVersion.cgi with v0 fallback`,
        'GET Solar API logger, inverter info, inverter realtime, power-flow, meter, Ohmpilot, storage, and active-device snapshots when supported by the device',
        'static snapshot/raw-data and injected client/executor operation',
      ],
      explicitUnsupported: [
        'Fronius Solar.web cloud APIs and historical cloud data',
        'pretending writes succeeded without an injected executor or client implementation',
        'non-Solar-API device administration endpoints',
      ],
    },
  };

  public async setup(configArg: IFroniusConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new FroniusRuntime(new FroniusClient(configArg));
  }

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

export class HomeAssistantFroniusIntegration extends FroniusIntegration {}

class FroniusRuntime implements IIntegrationRuntime {
  public domain = froniusDomain;

  constructor(private readonly client: FroniusClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    try {
      if (requestArg.domain === froniusDomain && (requestArg.service === 'snapshot' || requestArg.service === 'status')) {
        return { success: true, data: await this.client.getSnapshot() };
      }
      if (requestArg.domain === froniusDomain && 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 = FroniusMapper.commandForService(snapshot, requestArg);
      if (!command) {
        return { success: false, error: `Unsupported Fronius 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();
  }
}
