#!/usr/bin/env python3
"""
Try to decode the hidden message
"""

message = "8>,>LL>,e}TozKDMQEMELHOEKDLLDDDDDLLDDDIDDDDLDLDDDDDIDLLDID,>8888\\\\88888888888888888888888888888888888888888888>"

print("Original message:")
print(message)
print(f"Length: {len(message)}\n")

# Try reversing
print("=" * 80)
print("REVERSED:")
print("=" * 80)
reversed_msg = message[::-1]
print(reversed_msg)

if "HTB{" in reversed_msg:
    start = reversed_msg.find("HTB{")
    end = reversed_msg.find("}", start) + 1
    print(f"\n🚩 FLAG: {reversed_msg[start:end]}")

# Try Base64
print("\n" + "=" * 80)
print("BASE64 DECODE:")
print("=" * 80)
try:
    import base64
    decoded = base64.b64decode(message)
    print(decoded)
except Exception as e:
    print(f"Error: {e}")

# Try ROT13
print("\n" + "=" * 80)
print("ROT13:")
print("=" * 80)
import codecs
rot13 = codecs.encode(message, 'rot_13')
print(rot13)

if "HTB{" in rot13:
    start = rot13.find("HTB{")
    end = rot13.find("}", start) + 1
    print(f"\n🚩 FLAG: {rot13[start:end]}")

# Look for patterns - maybe it's hex?
print("\n" + "=" * 80)
print("ANALYZING PATTERNS:")
print("=" * 80)

# Check if certain characters repeat
char_counts = {}
for char in message:
    char_counts[char] = char_counts.get(char, 0) + 1

print("Character frequencies:")
for char, count in sorted(char_counts.items(), key=lambda x: x[1], reverse=True):
    print(f"  '{char}': {count}")

# Try extracting only certain characters
print("\n" + "=" * 80)
print("EXTRACTING PATTERNS:")
print("=" * 80)

# Maybe only uppercase letters spell the flag?
uppercase_only = ''.join([c for c in message if c.isupper()])
print(f"Uppercase only: {uppercase_only}")

if "HTB" in uppercase_only:
    print("Found HTB in uppercase!")

# Try looking for patterns in specific positions
print("\n" + "=" * 80)
print("TRYING DIFFERENT INTERPRETATIONS:")
print("=" * 80)

# Maybe the message before the long string of 8's is what matters
parts = message.split('8888')
print(f"Before '8888': {parts[0]}")

# Or maybe it's the D's and L's that matter (binary?)
binary_from_DL = message.replace('D', '0').replace('L', '1')
print(f"\nD->0, L->1: {binary_from_DL}")

# Try interpreting groups
words = []
current_word = ""
for char in message:
    if char in "DLI":
        current_word += char
    else:
        if current_word:
            words.append(current_word)
            current_word = ""
if current_word:
    words.append(current_word)

print(f"\nDLI groups: {words}")

# Maybe DLI is morse-like? D=dot, L=dash, I=space?
print("\n" + "=" * 80)
print("TRYING D/L/I AS MORSE-LIKE CODE:")
print("=" * 80)
print(f"Original DLI sequence: {' '.join(words)}")

# Or maybe it's a substitution cipher - let me try mapping to the most common letters
print("\n" + "=" * 80)
print("CHECKING FOR COMMON ENCODINGS:")
print("=" * 80)

# The '}' at position 8 suggests the flag might end there
# Let me extract around it
idx = message.find('}')
if idx >= 0:
    # Look backwards for HTB{
    before = message[max(0, idx-50):idx+1]
    print(f"Around closing brace: {before}")
    
    # Check if reversing from that point helps
    if idx >= 4:
        potential_flag = message[max(0, idx-50):idx+1]
        reversed_section = potential_flag[::-1]
        print(f"Reversed: {reversed_section}")
        
        if reversed_section.startswith("}"):
            print("Flag might be reversed!")
            # Look for {{BTH
            search = message[:idx+1][::-1]
            print(f"Reversed up to brace: {search}")
