package agentid

// Define a publisher interface for UCXL
type Publisher interface {
    Publish(address string, data []byte) error
}

// Define a subscriber interface for UCXL messages
type Subscriber interface {
    Subscribe(address string, handler func(data []byte)) error
}

func AnnounceAgentRecord(
    pub Publisher,
    agent *AgentRecord,
    leaderPubKey string,
) error {
    jsonPayload, err := agent.ToJSON()
    if err != nil {
        return err
    }

    encryptedPayload, err := EncryptPayload(jsonPayload, leaderPubKey)
    if err != nil {
        return err
    }

    ucxlAddress := "ucxl://any:admin@COOEE:enrol/#/agentid/" + 
        fmt.Sprintf("%d", agent.AssignedID)

    return pub.Publish(ucxlAddress, encryptedPayload)
}

func SetupAgentIDListener(
    sub Subscriber,
    privateKey string,
    handle func(*AgentRecord) error,
) error {
    ucxlAddress := "ucxl://any:admin@COOEE:enrol/#/agentid/*" // wildcard or prefix

    return sub.Subscribe(ucxlAddress, func(data []byte) {
        decrypted, err := DecryptPayload(data, privateKey)
        if err != nil {
            // handle error, log etc.
            return
        }
        agent, err := FromJSON(decrypted)
        if err != nil {
            // handle error, log etc.
            return
        }
        _ = handle(agent) // your context store merge or validation
    })
}
