#!/usr/bin/expect
# Set timeout for expect commands
set timeout 30

# Open the log file
log_file results.txt

proc expectit {pattern} {
    expect {
        $pattern {
            return
        }
        timeout {
            puts "Error: Expected response '$pattern' not received."
            send "quit\n"
            exit 1
        }
        eof {
            puts "Error: Connection closed unexpectedly."
            send "quit\n"
            exit 1
        }
    }
}

proc dont_expect {trigger pattern} {
    send "look\n"
    puts "NOTE: At this point, ** $pattern ** should not be here!"
}

# Get command line parameters
set there [lindex $argv 0]  ; # First parameter (boolean)   here/there
set tutorial [lindex $argv 1]  ; # Second parameter (optional)  yes/no
set create [lindex $argv 2]  ; # Third parameter (optional)  yes/no

if {$there eq "there"} {
    spawn ssh -p 4004 user@howardabrams.com
    # Handle the un-used password prompt:
    expectit "password:"
    send "\r"  ; # Send an empty password
} else {
    spawn telnet localhost 4000
}

# Handle the prompt after logging in
expectit "enclose it in quotes"

if {$create eq "true"} {
    send "create rob backinqa\n"
    expectit "Is this what you intended?"
    send "y\n"
    expectit "You can now log with the command"
}

send "connect rob backinqa\n"

if {$create eq "true"} {
    expectit "begin creating your character"
    send "\n"

    expectit "Let's begin with a two or three word description"
    send "spry goblin\n"

    expectit "Specifying the gender"
    send "n\n"

    expectit "Enter an initial pose"
    send "curiously looking at everything\n"

    expectit "Enter your character's full description"
    send "A short, skinny goblin wearing a dirty tunic cinched with an elaborate belt bejeweled with gems and gold filigree. Unclear whether his green ears or nose are longer, but surely it must be the few hairs he combs over on top of his head.\n"

    expectit "Enter a name here to check if it's available."
    send "Poach\n"

    expectit "Shall I create your character"
    send "y\n"
}

if {[string match "tutor*" $tutorial]} {
    # Handle the game command prompt
    expectit "In this story game, you type commands"
    send "look\n"

    # Handle the prompt to examine the puddle
    expectit "You can now type"
    send "look puddle\n"

    # Handle the response about flying
    expectit "Yes, I could fly myself"
    send "look boulder\n"

    # Handle the prompt about climbing the boulder
    expectit "You can climb this boulder!"
    send "climb\n"

    # Handle the prompt about typing
    expectit "Go ahead, just typing"
    send "say Hello there, little birdie.\n"
} else {
    expectit "perches on your shoulder"
}

# That should be enough of the birdie ...
send "shoo\n"

# Send the time command and handle the response
expectit "Have fun, and I'll leave you here"

send "time\n"
expect {
    "in the evening" {
        set phase "evening"
    }
    "in the afternoon" {
        set phase "afternoon"
    }
    "in the morning" {
        set phase "morning"
    }
    "in the night" {
        set phase "night"
    }
    timeout {
        puts "Error: Expected time response not received."
        send "quit\n"
        exit 1
    }
}

send "look\n"

# Expect different responses based on the phase variable
switch $phase {
    "evening" {
        expect "darkening twilight"
    }
    "afternoon" {
        expect "lazy afternoon"
    }
    "morning" {
        expect "awakening dawn"
    }
    "night" {
        expect "night sky"
    }
    default {
        puts "Error: Unexpected phase value '$phase'."
        send "quit\n"
        exit 1
    }
}

send "look trees\n"
expectit "You feel dwarfed by colossal trees"

send "look flowers\n"
expectit "Beautiful, but giant flowers look down on you and nod a friendly greeting."

send "hint\n"
expectit "Look at everything"

send "look puddle\n"
expectit "A large puddle"

send "get puddle\n"
expectit "As the water slips through your fingers"

send "jump\n"
expectit "You jump in the puddle!"

send "get stick\n"
expect {
    "Could not find 'stick'." {
        # Print warning in red
        # send_user "\033[31mNo stick, check the stick script.\033[0m\n"
        send_user "No stick, check the stick script.\n"
    }
    "You pick up a stick." {
        # If stick is found, throw it
        send "throw stick\n"
        expect "it comes back to you"

        send "drop stick\n"
        expect "You drop a stick."
    }
    timeout {
        puts "Error: Expected response for 'get stick' not received."
        send "quit\n"
        exit 1
    }
}

send "look book\n"
expectit "The root from one of the colossal"

send "look quill\n"
expectit "The black feathered quill may once belonged to a raven"

send "look ink\n"
expectit "Black, like the ichor of the gods"

send "look ink well\n"
expectit "The well appears to be little more than a depression"

send "read book\n"
# expect -re "You open the leather-bound book, and begin to read\[.\n\r\]*For repayment of a boon, The Summer Queen"
expectit "You open the leather-bound book, and begin to read"
expectit "For repayment of a boon, The Summer Queen"

expectit "revious"
# quit reading the book:
send "q\n"
expectit "Exited pager"
sleep 1

send "get book\n"
expectit "The owner designed a guest book to be read and written by guests"

send "look symbol\n"
expectit "You move an ivy runner to see three curves join together as if it were three legs."

send "look moss\n"
expectit "Even in this light, the moss radiates a surreal color of green."

send "look ivy\n"
expectit "You see...well, ivy. Uhm, it's green, and..."

send "look rune\n"
expectit "The runes read ᛞ ᚪ ᛒ ᛚ ᚱ"

dont_expect "Exits" "boulder"

send "look boulder\n"
expectit "You notice a foot hold"

send "look\n"
expect -re "Exits:.*climb.*boulder"

dont_expect "You notice.*" "vine"

send "look vine\n"
expectit "Strong vines twisted to look like rope"

send "look\n"
expect -re "You notice.*vines"

send "get vine\n"
expectit "The vines are too strong to break or cut."

send "pull vine\n"
expectit "You pull the vines, but they don't let go."

send "push vine\n"
expectit "That doesn't seem to do much."

send "climb boulder\n"
expectit "You grab hold of some"

# Did we arrive?
expectit "Boulder Top"

send "look trees\n"
expectit "You feel dwarfed by colossal trees"

send "look down\n"
expectit "The climb seemed easy, but you're not sure you can handle the footholds going the other way around."

send "look moss\n"
expectit "A cushioned patch of moss of the most vibrant green."

send "sit moss\n"
expectit "You sit on the patch of moss."

# We can't get this stuff:
send "get moss\n"
expectit "The moss is a bryophyte"

send "look vines\n"
expectit "While difficult to cut, the study and tough vines are easy to pull"

send "pull vines\n"
expectit "You pull the vines"

send "get vines\n"
expectit "You yank and shape a coil of rope from the vines"

send "inv\n"
expectit "Made from vines"

# Let's get another length of rope to try lassoing the hut twice:
send "get vines\n"
expectit "You yank and shape a coil of rope from the vines"

# Let's head back to the grove...
send "down\n"
expectit "You stand up first"

# Wait until we've arrived
expectit "Grove of the Matriarchs"

dont_expect "You notice" "mushrooms"

send "e\n"
expectit "Frog Meadow"

# Until we are an alchemist, we shouldn't see the tickleweeds...
dont_expect "You notice" "tickleweed"

send "look frogs\n"
expectit "Cute little guys"

dont_expect "Exits" "cave entrance"

dont_expect "You notice" "waterfall"

send "look pool\n"
expectit "A pool of cool, clear water."

send "look waterfall\n"
expectit "entrance hidden behind the water?"

# water == waterfall ... eh.
# send "look water\n"
# expectit "Could not find 'water'"

send "look\n"
expect -re "Exits:.*cave entrance"
expect -re "You notice.*waterfall"

send "get waterfall\n"
expectit "You can't get that"

send "look stream\n"
expectit "A slow-moving stream meanders like a snake in the grassy field."

send "get stream\n"
expectit "Seriously? You can't get that."

dont_expect "You notice" "tickleweed"

send "hint\n"
expectit "but scared of everything and everyone"
send "hint beast\n"
expectit "The beast doesn't like new people"
send "hint feed\n"
expectit "Just hard to get into his house"
send "hint berries\n"
expectit "You'll find a bush of them to the west in the Grotto"
send "hint scones\n"
expectit "Dabbler lives in a tree to the west, behind a red door"
send "hint stream\n"
expectit "Yes, the fizzy water is drinkable"
send "hint collect\n"
expectit "To collect the water, you will need"
send "hint bottle\n"
expectit "to collect the water."

send "look cave\n"
expectit "A large entrance to a dark, and foul-smelling cave."

send "lair\n"
expectit "Lair"

send "look outside\n"
expectit "You can see the waterfall cascading outside the cave entrance."

dont_expect "You notice" "mattress"

send "look mattress\n"
expectit "Looks comfortable"

send "look\n"
expect -re "You notice.*mattress"

send "sit\n"
expectit "You sit on the mattress."

send "get mattress\n"
expectit "too heavy"

dont_expect "You notice" "mushrooms"

send "leave\n"
expectit "Frog Meadow"

expect {
    "a big hairy beast" {
        send "look beast\n"
        expectit "it tries to hide behind a tall clump of grass"

        send "pet bhb\n"
        expectit "can't get near"

        send "get hairy beast\n"
        expectit "beast is far larger than you."

        send "feed beast\n"
        expectit "doesn't appear interested in anything you have."
    }
    timeout {
        if {$phase == "night"} {
            puts "The beast is in bed now."
        } else {
            puts "Where is the beast? It is $phase?"
        }
    }
}

send "look south\n"
expectit "Looks like the river spreads into a marsh."

send "south\n"
expectit "perched on three"

send "look north\n"
expectit "The meadow to the north looks easier to walk around."

send "look birds\n"
expectit "Birds of every color on the rainbow and beyond fly and squawk around you"

send "look moth\n"
expectit "On closer inspection, the moths are really"

send "look sprite\n"
expectit "Seems that sprites with pink wings are on one team"

send "look fireflies\n"
expectit "A passing firefly shows it to actually be"

send "look pixies\n"
expectit "The pixies ignore you as their coreography keeps them focused on their dance."

send "look grass\n"
expectit "Guess this kind of grass doesn't mind the wet environment."

send "hut\n"
expectit "the hut scurries away"

send "use 1-rope\n"
expectit "Something tells you that the rope won't last for long."

send "look\n"
expectit "A pissed-off looking"

send "look hut\n"
expectit "straining at its bonds"

send "hut\n"
expectit "The door, and its landing, are still too high and out of reach"

# Let's wait to make sure that the hut eventually breaks free ...
puts "Waiting for the hut to break free of its bonds..."
set timeout 90
expectit "The hut, straining against its bounds, finally breaks free"
set timeout 30

send "look river\n"
expectit "A muddy, almost stagnant river."

# The 'get water' should work, but issues with aliases...
send "get river\n"
expectit "Slippery things, those rivers."

send "say Hello there, big bird.\n"
expectit "heron"

send "get heron\n"
expectit "flies out of reach"

send "look reeds\n"
expectit "Extremely tall, white reeds tipped with white gooey clumps."

send "get reeds\n"
expectit "You pluck and shape a ten-foot pole from a marsh reed"

dont_expect "You notice" "pixie dust"

send "use rope on hut\n"
expectit "Something tells you that the rope won't last for long."

send "hut\n"
expectit "Homey Hut"

send "look jar\n"
expect -re "You look at one.*labeled"

dont_expect "You notice" "skull"

send "look skull\n"
expectit "Painted with arcane symbols, a wolf skull sports"

send "look\n"
expect -re "You notice.*skull"

send "get skull\n"
expectit "It appears firmly attached to the wall where it hangs."

dont_expect "You notice" "carving"

send "look carving\n"
expectit "the carving shows exquisite craftsmanship and artistry"

send "look\n"
expect -re "You notice.*carving"

send "get carving\n"
expectit "As you reach for the carving, it promptly runs away."

dont_expect "You notice" "reed"

send "look reed\n"
expectit "twisted and shaped in a six-spoke star"

send "look\n"
expect -re "You notice.*reed"

send "get sculpture\n"
expectit "It appears firmly attached to the wall where it hangs."

send "get torch\n"
expectit "You take a torch from the bucket."

send "inv\n"
expectit "Made from marsh grass"

puts "Waiting for Trampolina to sweep us out the door..."
set timeout 240
# expectit "grabs her broom and with a sweeping motion"
expectit "Mellow Marsh"
set timeout 20

send "north\n"
expectit "Frog Meadow"

send "west\n"
expectit "Grove of the Matriarchs"

send "look south\n"
expectit "You see a dock on a lavender sea"

send "south\n"
expectit "Lazy Dock"

send "look north\n"
expectit "This path leads into the forest of collosal trees."

send "look boat\n"
expectit "The mastless ship looks like a giant leaf. Wonder if it comes to shore?"

send "look waves\n"
expectit "Despite the inclement weather, the waves ripple softly against the shore."

send "look sea\n"
expectit "A gently waving sea."

# This should be 'get water'!
send "get sea\n"
expectit "You can only hold the sea in your heart."

send "look chair\n"
expectit "A cushioned wood chair of craftsmanship"

send "sit\n"
expectit "You sit on the chair."

send "stand\n"
expectit "You stand up"

send "get chair\n"
expectit "way too heavy for you to lift."

send "get pole\n"
expectit "You pick up a fishing pole."

send "cast\n"
expectit "You cast"

send "reel\n"
# Too many messages to expect.

send "drop fishing pole\n"
expectit "You drop a fishing pole."

send "look sign\n"
expectit "You see a wood sign tied with a rope around the back of the chair"

send "read sign\n"
expectit "Fish at your own annoyance. Please return pole when finished."

send "get sign\n"
expectit "This granny knot"

send "hint\n"
expectit "Docks are good"
send "hint fishing\n"
expectit "If you dare catch"
send "hint fish\n"
expectit "You can get rid of obnoxious fish"
send "hint boat\n"
expectit "A magical boat appears here"
send "hint call\n"
expectit "To call the boat"
send "hint swamp\n"
expectit "I think the swamp is called"
send "hint horn\n"
expectit "The mystical south wind gathers the mystical mist from the sea"

# Currently at Lazy Dock
send "look south\n"
expectit "You see a shack down along the sandy shore."

send "south\n"
expectit "Shore"

send "look north\n"
expectit "The sandy shore to the north ends at a dock, jutting into the lavender sea."

send "look waves\n"
expectit "Despite the inclement weather, the waves ripple gently against the shore."

send "look lavender sea\n"
expectit "you see sailing the sea in the distance?"

send "look boat\n"
expectit "The mastless ship looks like a giant leaf. Wonder if it comes to shore?"

send "look shack\n"
expectit "Standing crookedly at the edge of the sandy shore, this shack's weathered planks"

dont_expect "You notice" "sand"

send "look sand\n"
expect -re "You notice.*sand"

send "get sand\n"
expectit "You fill a small bag of sand"

send "look sign\n"
expectit "A hand-painted sign with beautiful calligraphy reads"

send "read sign\n"
expectit "For Rent. See Dabbler for details."

send "get sign\n"
expectit "You can't get that."

send "look door\n"
expectit "Barnacle encrusted door with rusty irons bands and a comically large padlock."
#
send "door\n"
expectit "The door is obviously locked."

send "north\n"
expectit "Lazy Dock"

send "north\n"
expectit "Grove of the Matriarchs"

send "look west\n"
expectit "A footpath winds between the roots of a tree."

send "west\n"
expectit "Grotto"

send "look east\n"
expectit "A winding footpath leads through the forest of giant trees."

send "look tree\n"
expectit "The trees in this forest are massive, but a smaller tree has a red door."

send "look bridge\n"
expectit "bridge leads over a tiny"

send "look cabbage\n"
expectit "Large glossy green leaves with big yellow flowers that looks like cobras in drag"

send "look ferns\n"
expectit "Sword ferns rattling sabers against the wards from the Maiden Hairs' flailing their fronds."

send "pick berries\n"
expectit "You pick"

send "eat berry\n"

send "get berry\n"
expectit "You pick"

send "eat berry\n"

send "look stream\n"
expectit "A small stream, almost hidden behind the ferns and brambleberry bushes"

# send "get water\n"
send "get stream\n"
expectit "Seriously? You can't get that."

send "knock\n"
expectit "You grab the ring"

send "get ring\n"
expectit "From whom do you want to get this ring?"

send "get ring from knocker\n"
expectit "You take brass ring from knocker."

send "say Give me a hint, please.\n"
expectit "A hint does sound fair."

send "say Is the answer, whiskey?\n"

send "give ring to knocker\n"
expectit "You give a brass ring to knocker."

send "hint\n"
expectit "So try to talk to it."

send "inside\n"
expectit "Cozy House"

expectit "The subtle smell of wood smoke, incense and fresh-baked scones"

send "look tapestry\n"
expectit "The muted colors of the tapestry"

send "look man\n"
expectit "The old man in the"

send "look rose\n"
expectit "The rose in both scenes"

send "look queen\n"
expectit "The beautiful queen shown in the second scene"

send "look paper\n"
expectit "The paper with a gold seal"

send "look trees\n"
expectit "The trees shown in the third and fourth scenes"

send "look whispering\n"
expectit "This curious aspect"

send "get wood\n"
expectit "You get a small log from the wood rack."

send "feed log to fire\n"
expect "You start a fire"

send "look trinkets\n"
expectit "."

# First time, we get the full description:
send "look books\n"
expectit "Shelves at various angles embellish the walls of this small, cozy room."

# Second time, we get a shorter message:
send "look book\n"
expect -re "You .*book.*titled"

send "get book\n"
expectit "You pick up the book"

send "read book\n"
expect -re "You.*open your book"

send "drop book\n"
expectit "flies"

send "sit\n"
expectit "You sit in "

send "hint\n"
expectit "You are in a cozy and casual place"

send "pet beastie\n"
expectit "beastie"

send "feed beastie\n"
expectit "beastie doesn't appear interested in anything you have."

send "kitchen\n"
expectit "Cramped Kitchen"

send "look scones\n"
expectit "look tempting"

send "get scone\n"
expect -re "You get.*scone"

send "eat scone\n"
# Too much variableness here.
# expectit "You"

send "make green\n"
expectit "You make a teapot"

send "pour tea\n"
expectit "Command 'pour tea' is not available."

send "get teacup\n"
expectit "You pick up a teacup."

send "look teacup\n"
expectit "Teacup"

send "pour tea\n"
expect -re "You pour some.*cup"

send "drink tea\n"
expect -re "You.*cup"

send "pour tea\n"
expect -re "You empty your teacup"

send "hint\n"
expectit "Grab yourself some breakfast"

send "leave\n"
expectit "Cozy House"

dont_expect "You notice" "sconce"

send "look sconce\n"
expectit "A black iron sconce holding a single"

send "look\n"
expect -re "You notice.*sconce"

send "get candle\n"
expectit "You take the candle, but another magically appears in its place"

send "pull sconce\n"
expectit "You hear a click, and the bookcase next to the candle swings forward revealing"

send "look\n"
expect -re "Exits:.*stairs behind bookcase"

send "look stairs behind bookcase\n"
expectit "Behind the protruding bookcase, you see a staircase leading down into the darkness."

send "down\n"
expectit "Secret Room"

send "look stairs\n"
expectit "Stone steps leading back to the surface."

send "look table\n"
expectit "Made from a polish black wood, etched with intricate runes that shimmer faintly in the candlelight."

send "look alchemical equipment\n"
expectit "all surround a black"

send "look mortar and pestle\n"
expectit "An obsidian mortar, its surface smooth and cool to the touch."

send "look vials\n"
expectit "Scattered across a small shelf, an array of empty glass vials."

send "look phials\n"
expectit "Delicate crystal phials, each shaped like a teardrop, attach to a wrought iron rack."

send "look tools\n"
expectit "A set of finely crafted tools lies neatly arranged on a velvet cloth"

send "look jar\n"
expect -re "You look at one.*labeled"
#
send "look jar\n"
expect -re "You look at one.*labeled"

send "look stool\n"
expectit "A place to sit while synthesizing experiments."

send "sit\n"
expectit "You sit on the stool."

send "stand\n"
expectit "You stand up"

send "get stool\n"
expectit "Stop trying to steal everything not nailed down."

send "look grimoire\n"
expectit "An old brown book where even the cover has seen considerable wear with stains and scratches in the leather."

send "read book\n"
expectit "Undoing the brass clasp that bind the old leather book"

send "get book\n"
expectit "The book is chained to the table."

send "look cauldron\n"
expectit "A small, cast-iron cauldron sits on an iron stand, its interior stained from countless brews."

send "get cauldron\n"
expectit "You can't get that."

send "look shelf\n"
expectit "Cluttered with some empty brown"

send "get bottle\n"
expectit "You pick up a bottle."

send "look imp\n"
expectit "Peculiar little fellow gives you are quizical look from its roost"

send "say Hello there, little guy.\n"
expect -re "Imp"

# We left our tester in the Secret room, so ...
send "leave\n"
expectit "Cozy House"

send "look up stairs\n"
expectit "Ornate black irons banister outline the thick wood planks that form steps leading to some lofty alcove."

send "up\n"
expectit "Bedroom"

send "look down stairs\n"
expectit "Ornate black irons banister outline the thick wood planks that form steps leading down to living space below."

send "look slippers\n"
expectit "Red-leather and worn with an ornate tassel on top."

send "get slippers\n"
expectit "You pick up a pair slippers."

# Make sure we start this test with a closed wardrobe:
send "close wardrobe\n"
expectit "closed."

send "look wardrobe\n"
expectit "While resting on the floor, this wardrobe scratches the ceiling. Large furniture, or perhaps a small room?"

send "get wardrobe\n"
expectit "The wardrobe is way too big to lift."

send "open wardrobe\n"
expectit "You open the wardrobe, revealing the cloaks, jackets, and"

send "look through the wardrobe\n"
expectit "Behind the cloaks and jackets, you see long, green needles from pine trees, and beyond that, a clearing!"

send "wardrobe\n"
expectit "Prairie"

send "look copse\n"
expectit "A copse of trees covers the top of the knoll."

send "look knoll\n"
expectit "The land stretches and buckles in small rolls."

send "look lantern\n"
expectit "Curious iron worked lantern sways in the subtle breeze."

send "look campfire\n"
expectit "Only a thin wisp of smoke escapes to the skies; fragrating the air."

send "look figure\n"
expectit "A curious figure wearing dark robes and a gleaming white skull of a mare."

send "look ears\n"
expectit "They look real, and twitch as if alive."

puts "Waiting to get a pipe as a gift."
set timeout 240
expectit "gives you a pipe"
set timeout 20

send "sit\n"
expectit "You sit on the long log"

send "copse\n"
expectit "Bedroom"

send "close wardrobe\n"
expectit "The wardrobe door is closed."

send "down\n"
expectit "Cozy House"

send "leave\n"
expectit "Grotto"

send "east\n"
expectit "Grove of the Matriarchs"

send "climb boulder\n"
expectit "Boulder Top"

send "look patch of mushrooms\n"
expectit "A vibrant patch of mushrooms bursts forth like a painter's palette, each cap shimmering with iridescent hues of violet, emerald, and gold"

send "get mushroom\n"
expectit "You harvest a gigglecap mushroom."

send "climb down\n"
expectit "Grove of the Matriarchs"

send "east\n"
expectit "Frog Meadow"

send "look tickleweed\n"
expectit "Patches of this vivid grass vibrates as if giggling."

send "get tickleweed\n"
expectit "You harvest a bunch of tickleweed."

send "fill bottle\n"
expectit "you fill it with sparkling water"

# Head to secret lab...
send "west\n"
expectit "Grove of the Matriarchs"

send "west\n"
expectit "Grotto"

send "red door\n"
expectit "Cozy House"

send "pull sconce\n"
expectit "You hear a click"

send "down stairs\n"
expectit "Secret Room"

send "empty\n"
expectit "empty"

send "add mushroom\n"
expectit "You add gigglecap mushroom to black cauldron."

send "add tickleweed\n"
expectit "You add bunch of tickleweed to black cauldron."

send "add bottle\n"
expectit "You pour the fizzy water from your bottle into the black cauldron."

send "create\n"
expectit "making it ready"

send "bottle\n"
expectit "You fill a small vial"

send "inventory\n"
expectit "vial"

send "empty\n"
# Since almost anything can be written, we look for a period
expectit "."

send "empty\n"
expectit "The black cauldron is already empty."

send "up\n"
expectit "Cozy House"

send "score\n"
expectit "Total:"

send "give potion to gnome\n"
expectit "You give a potion"

# Close the log file
log_file

sleep 1
send "quit\n"

# Handle the connection closed message without logging it
expect {
    "Connection closed by foreign host" {
        # Ignore this response
        exp_continue
    }
    eof {
        # End the session
        return
    }
}
