namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS;

/// <summary>
///     Parsed FOCAS target address — IP + TCP port. Canonical <c>focas://{ip}[:{port}]</c>.
///     Default port 8193 (Fanuc-reserved FOCAS Ethernet port).
/// </summary>
public sealed record FocasHostAddress(string Host, int Port)
{
    /// <summary>Fanuc-reserved TCP port for FOCAS Ethernet.</summary>
    public const int DefaultPort = 8193;

    public override string ToString() => Port == DefaultPort
        ? $"focas://{Host}"
        : $"focas://{Host}:{Port}";

    public static FocasHostAddress? TryParse(string? value)
    {
        if (string.IsNullOrWhiteSpace(value)) return null;
        const string prefix = "focas://";
        if (!value.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return null;

        var body = value[prefix.Length..];
        if (string.IsNullOrEmpty(body)) return null;

        var colonIdx = body.LastIndexOf(':');
        string host;
        var port = DefaultPort;
        if (colonIdx >= 0)
        {
            host = body[..colonIdx];
            if (!int.TryParse(body[(colonIdx + 1)..], out port) || port is <= 0 or > 65535)
                return null;
        }
        else
        {
            host = body;
        }
        if (string.IsNullOrEmpty(host)) return null;
        return new FocasHostAddress(host, port);
    }
}
