import { FieldType, type Segment } from "@hamradio/packet";

import { DataType, type Payload, type StationCapabilitiesPayload } from "./frame.types";

export const decodeCapabilitiesPayload = (
  raw: string,
  withStructure: boolean = false
): {
  payload: Payload | null;
  segment?: Segment[];
} => {
  try {
    if (raw.length < 2) return { payload: null };

    // Extract the text after the '<' identifier
    let rest = raw.substring(1).trim();

    // Some implementations include a closing '>' or other trailing chars; strip common wrappers
    if (rest.endsWith(">")) rest = rest.slice(0, -1).trim();

    // Split capabilities by commas, semicolons or whitespace
    const tokens = rest
      .split(/[,;\s]+/)
      .map((t) => t.trim())
      .filter(Boolean);

    const payload: StationCapabilitiesPayload = {
      type: DataType.StationCapabilities,
      capabilities: tokens
    } as const;

    if (withStructure) {
      const segments: Segment[] = [];
      segments.push({
        name: "capabilities",
        data: new TextEncoder().encode(rest).buffer,
        isString: true,
        fields: [
          {
            type: FieldType.STRING,
            name: "capabilities",
            length: rest.length
          }
        ]
      });

      for (const cap of tokens) {
        segments.push({
          name: "capability",
          data: new TextEncoder().encode(cap).buffer,
          isString: true,
          fields: [
            {
              type: FieldType.STRING,
              name: "capability",
              length: cap.length
            }
          ]
        });
      }

      return { payload, segment: segments };
    }

    return { payload };
  } catch {
    return { payload: null };
  }
};

export default decodeCapabilitiesPayload;
