package main

import (
	"fmt"
	"os"
	"strings"
)

const (
	PUA_START = 0xE0000
)

func encodeHiddenMessage(message string) string {
	var hidden strings.Builder
	for _, char := range message {
		hidden.WriteRune(PUA_START + char)
	}
	return hidden.String()
}

func decodeMixedMessage(input string) string {
	var decoded strings.Builder
	var hiddenBuffer strings.Builder
	inHiddenSequence := false

	for _, char := range input {
		if char >= PUA_START && char < PUA_START+0xFFFF {
			if !inHiddenSequence && hiddenBuffer.Len() > 0 {
				decoded.WriteString(hiddenBuffer.String())
				hiddenBuffer.Reset()
			}
			inHiddenSequence = true
			hiddenBuffer.WriteRune(char - PUA_START)
		} else {
			if inHiddenSequence {
				decoded.WriteString(hiddenBuffer.String())
				hiddenBuffer.Reset()
				inHiddenSequence = false
			}
			decoded.WriteRune(char)
		}
	}

	if hiddenBuffer.Len() > 0 {
		decoded.WriteString(hiddenBuffer.String())
	}

	return decoded.String()
} 

func main() {
	if len(os.Args) < 3 {
		fmt.Println("Usage:")
		fmt.Println("  Encode: go run main.go encode \"secret message\"")
		fmt.Println("  Decode: go run main.go decode \"󠁳󠁥󠁣󠁲󠁥󠁴\"")
		os.Exit(1)
	}

	command := os.Args[1]
	text := strings.Join(os.Args[2:], " ")

	switch command {
	case "encode":
		hidden := encodeHiddenMessage(text)
		fmt.Printf("Encoded: %s\n", hidden)
	case "decode":
		decoded := decodeMixedMessage(text)
		fmt.Printf("Decoded: %s\n", decoded)
	default:
		fmt.Println("Invalid command. Use 'encode' or 'decode'.")
		os.Exit(1)
	}
}
