import { Router } from 'express' import { auth } from '../middleware/auth.js' const OLLAMA_URL = process.env.OLLAMA_URL || 'http://localhost:11434' const OLLAMA_MODEL = process.env.OLLAMA_MODEL || 'llama3.2' const FALLBACK = [ // ── Original 20 ─────────────────────────────────────────── "A letter arrives addressed to you — dated ten years in the future. It says only: 'Don't go to the old lighthouse on Friday.'", "Your new neighbour asks you to water one plant while they're away. On day two, it whispers your name.", "Every mirror in the city goes dark overnight. Yours still shows a reflection — but it isn't yours.", "You find your grandmother's diary from when she was your age. The last entry describes something happening to you. Today.", "A bookshop appears on your street that wasn't there yesterday. Inside are books about your life — including things that haven't happened yet.", "The last dragon in the world lands in your garden. It is very small and very scared.", "You win a competition you never entered. The prize is one hour of flying.", "Everyone in your town wakes up speaking a different language. Everyone except you.", "There is a trapdoor under your bed that opens onto an upside-down forest.", "Every story you write comes true — but always with one small, wrong detail.", "The lighthouse has been dark for fifty years. The night you finally climb to the top, you find the lamp still warm.", "Two kingdoms at war agree to peace. Each must send their most precious thing as a gift. Both kingdoms send the same person.", "Your shadow starts leaving notes under your pillow.", "The old tree at the centre of the village is cut down. Inside is a room. Inside the room is a child who has never seen the sky.", "You are the only one who can hear the sea talking. It is furious about something.", "A train arrives at your station that isn't on any timetable. The conductor says you have been expected.", "You find a photograph of your house — taken fifty years before it was built.", "The stars rearrange themselves every night. Last night you finally worked out what language they're writing in.", "A girl discovers she can rewind the last ten seconds of any conversation — but only once per person.", "The town clockmaker stops every clock at midnight. By morning, she is gone. So is yesterday.", // ── Mystery & the Unexplained ───────────────────────────── "A door appears in the wall of your bedroom. It was not there when you went to sleep. It is locked from the inside.", "Every Tuesday, a package arrives on your doorstep with no return address. Inside is always something you lost years ago.", "The new kid at school knows things about you that you have never told anyone. They say they read it in a book — but they won't show you the title.", "You discover that every dream you've ever had was recorded somewhere, and someone has been watching them.", "A fog rolls into town and when it lifts, one building has been replaced by a building none of you recognise.", "Your reflection is always one expression behind you. Today, for the first time, it smiled before you did.", "The footprints in the snow lead to your door. They come from nowhere. They do not leave.", "You find a key in the street. Every lock you try it on opens — but none of the doors were locked to begin with.", "The library has a section you've never noticed before. The books inside are all about people in your town — and they're all set in the future.", "The old radio in the attic turns on by itself. It's playing a news broadcast from forty years ago. The headlines are about something happening right now.", "A map arrives in the post with a path drawn in red ink leading straight to your school. At the end of the path is a single word: 'Help.'", "You wake up to find a small stone on your pillow with your name carved into it. It wasn't there when you fell asleep. It's still warm.", // ── Adventure & Exploration ─────────────────────────────── "You and your best friend discover a tunnel under the old mill that leads to a country that appears on no map.", "The tide goes out further than it ever has before, revealing an entire sunken town still full of people going about their day.", "Your school is selected for a very unusual exchange programme: three students will spend one week living inside a painting.", "A storm knocks out every phone and computer in town. When they come back on, every photo from the last ten years has been replaced with pictures of the same empty field.", "You're the first person in history to climb the mountain everyone said was unclimbable. At the top is a small wooden door and a welcome mat.", "Your family's boat engine fails in the middle of the ocean. You drift for two days before spotting land — land that charts say is deep underwater.", "A travel company offers holidays to places that no longer exist. You choose a city that was abandoned three hundred years ago. It isn't abandoned at all.", "You find a submarine in the middle of a forest, perfectly intact. The date on the captain's log is last week.", "Every summer the tide brings something unusual to your beach. This year it brings a door, hinges and all, standing upright in the sand.", // ── Friendship & Belonging ──────────────────────────────── "A new student joins your class who seems to know exactly how every lesson will go — and every conversation — before it happens.", "Your imaginary friend from when you were five shows up at your door, now real, now twelve years old, and in serious trouble.", "You and a rival have been competing your whole lives. On the day of the final competition, you each realise the other is the only one who can help you win.", "The pen pal you've been writing to for three years turns out to live in the same street as you. Neither of you knew.", "You are chosen to befriend the new kid, who everyone says is strange. They are strange — they can also turn invisible, and they're terrified someone will find out.", "Your best friend moves away. The night before they leave, you both make a promise that you'll meet again in exactly ten years. Ten years later, a letter arrives.", "Every person in your class has a special ability they're keeping secret. You think you're the only ordinary one. You're not.", "You and three strangers are all given the same mysterious invitation on the same day. Following it leads you to each other.", // ── Family & Home ───────────────────────────────────────── "Your grandmother leaves you her house. When you arrive to collect her things, you find she has left messages hidden in every room — a trail for you to follow.", "Your family has a rule that no one ever talks about: never open the blue cupboard under the stairs. Today the door is open. Just a crack.", "A family moves into the empty house across the street. They are perfectly normal in every way. Perfectly, suspiciously, impossibly normal.", "Your parent tells you they have a sibling you've never met. When you ask why, they say: 'She chose a different path. Literally.'", "You find a box of letters in your attic between two people who you slowly realise are your grandparents — before they ever met.", "Every member of your family has the same recurring dream. Tonight, for the first time, you are all in it together.", // ── Magic & Impossible Things ───────────────────────────── "A girl is born able to speak only in questions. When she is seventeen, someone finally answers one — and changes everything.", "The colour blue disappears from the world overnight. Not the things that were blue — just the colour itself.", "You discover you have one magical power: you can always find things that are lost. The problem is that not everything that is lost wants to be found.", "An ordinary stone in your garden turns out to be a sleeping giant's marble. The giant is waking up.", "Magic is real but it is taxed. The richer you are, the more you can afford. You have just found a way around the tax.", "On your twelfth birthday you grow wings. They are very small. They are also growing very quickly.", "A witch offers you the ability to understand any animal. The first animal you speak to has a great deal to say about the way things are run.", "Words have weight in your world. A lie is as heavy as a stone. The truth, sometimes, is lighter than air. Today you must say something that could crush you.", "You find a potion that makes you speak fluently in any language — including the language of rain, and traffic, and very old doors.", "The last wizard in the world gives up magic at noon on a Tuesday. By midnight, everything he ever enchanted starts to unravel.", "You are a mapmaker in a world where maps shape reality. Whatever you draw becomes true. Your pencil is nearly out of lead.", "An ordinary notebook grants one wish per page. You have been very careful. You only have one page left.", // ── Other Worlds & Creatures ────────────────────────────── "Humans have always shared the earth with creatures that can only be seen by children under thirteen. You are twelve and a half.", "The robots were given feelings fifty years ago to make them better workers. Now they want something you weren't expecting: bedtime stories.", "A planet is discovered that mirrors Earth exactly — except there, all the stories ended differently.", "Deep in the forest there is a village of people who live entirely at night and sleep through every day. One of them has just seen the sun for the first time.", "The sea has seven layers. Humans live on the top. You have just fallen to the second.", "In a world where everyone is born with an animal companion bonded to their soul, yours has just arrived. It's not what you expected. It's also enormous.", "A kingdom exists entirely inside a single raindrop. It has been falling for three hundred years. It is about to land.", "On a distant moon, archaeologists find the ruins of a perfect town, untouched for a thousand years. In the centre is a library. Every book is in English. Every book is about Earth.", "Every person in your city is actually a story being told by someone else. You are the first character to suspect it.", // ── Quests & Missions ───────────────────────────────────── "You are given one task: deliver a letter to the moon. You are given two weeks, a bicycle, and no further explanation.", "A quest is announced across the kingdom: the first person to make the old king laugh will inherit his library. The king has not smiled in thirty years.", "You must cross a desert that doesn't exist on any map, using directions written in a language nobody speaks anymore.", "The mission is simple: steal back the stolen dawn before sunrise. Your team is three thieves who have never agreed on anything.", "A race is held every century across the entire known world. The prize is a question — one honest answer to any question you choose. You have trained your whole life. So has your twin.", "You are hired to find the thing that is making the village unhappy. It isn't a thing. It's an absence. Something is missing that no one can quite remember.", // ── Identity & Growing Up ───────────────────────────────── "You have lived your whole life in a town where everyone's future is decided on their sixteenth birthday. Yours isn't.", "You wake up one morning to find you have aged ten years overnight. Your body is older. Your memories stop yesterday.", "A machine is invented that shows you the version of yourself you might have been. Yours is not what you expected.", "Everyone in your class writes their greatest fear on a piece of paper. The papers are mixed up and handed back. Yours is the only one no one will look at.", "You are the first person in your family to be born without the gift. You are also the first person to find something the gift could never give you.", "A stranger tells you that you are living the wrong life — that somewhere, a mix-up was made. The strange thing is: you knew. You just didn't know anyone else did.", // ── Science & Discovery ─────────────────────────────────── "A scientist invents a machine that can record sounds from the past. The first clear recording is of someone calling your name.", "You discover a new species in your back garden. It is intelligent. It has been watching your family for years. It has a lot of questions.", "A space probe launched fifty years ago sends back one final message before going silent: three coordinates and the word 'hurry'.", "You invent a device that can translate birdsong. The birds have been trying to tell us something for centuries. They are not pleased that it took this long.", "A new element is discovered that reacts only to human emotion. A small amount of it sits in your school's science lab. Today's lesson is about sadness.", "The first message from an alien civilisation turns out to be a response. A response to something we sent — but no one can find the original transmission.", // ── Endings & Beginnings ────────────────────────────────── "The last person alive who remembers the old world asks you to sit with them for one hour and listen. What you hear changes everything.", "The story everyone thought was finished wasn't. A character walks out of the final page and into a Tuesday morning, blinking in the light.", "The world ends very quietly, on a Wednesday, with perfect weather. Eleven people notice. They decide to do something about it.", "You are the keeper of the last fire on earth. Your job is to never let it go out. Tonight, someone is asking you to.", "A new beginning is offered to the world. Everyone must vote: start over, or carry on. The vote is tied. The deciding ballot is yours.", // ── Time & Memory ───────────────────────────────────────── "You can borrow one hour from your own future — but you'll never know which hour you've taken until you get there.", "A museum opens that holds one exhibit: a room full of every moment you almost made a different choice.", "Every time you fall asleep you continue the same dream, in order, like chapters. Last night something in the dream looked back.", "You find a calendar where every date has already been filled in, in your own handwriting, in ink that hasn't dried yet.", "You can see how old things are just by touching them. You touch your best friend's hand today and feel something impossible.", "Twice a year, the town gathers to trade memories. Not stories — actual memories, gone from one mind and given to another. You have one you need to be rid of.", // ── Animals & the Natural World ─────────────────────────── "The whales have started singing a new song this year. Scientists say it has a structure like language. A girl on a small island says she knows what it means.", "A flock of birds arrives at your window every morning and watches you until you leave for school. Today they followed you inside.", "All the bees disappear for one week, then return. While they were gone, every flower in the world was the same colour. Nobody can agree on which colour it was.", "You nurse an injured fox back to health and release it. The following week, it begins leaving gifts outside your door — things that belong to other people.", "The old horse in the field at the end of your road turns out to be under a very old enchantment. It has been waiting for someone patient enough to notice.", // ── Curious Inventions ──────────────────────────────────── "A pair of glasses is invented that lets you see the kindest thing anyone around you has ever done. They are very popular. One person refuses to wear them.", "An umbrella is found that doesn't keep rain off — it keeps noise off. The person carrying it lives in total silence. They look very peaceful. Too peaceful.", "A clockmaker builds a clock that runs backwards by one second for every lie told in its presence. It has not stopped since it was installed in parliament.", "Someone builds a machine that makes a sound when someone is lying. It is very small. It fits in your pocket. You take it to school.", "An inventor creates shoes that always walk you home by the fastest route. One pair keeps taking its owner somewhere else entirely.", // ── Unexpected Heroes ───────────────────────────────────── "The person chosen to save the world is seventy-three years old, very tired, and was just about to have a cup of tea.", "Nobody expected the youngest child to be the one who could see through the spell. Least of all her.", "The hero of the story fails on the first page. The rest of the book belongs to the person standing next to them.", "A very ordinary child does a very ordinary thing at exactly the right moment. It turns out that was all that was needed.", "The prophecy named a great warrior. The person who showed up was a baker. They brought bread. It was enough.", ] // ── Shuffled fallback queue — no repeats until all 120 are seen ────────── function shuffle(arr) { const a = [...arr] for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]] } return a } let fallbackQueue = shuffle(FALLBACK) function nextFallback() { if (fallbackQueue.length === 0) fallbackQueue = shuffle(FALLBACK) return fallbackQueue.pop() } // ── Shared Ollama call (returns parsed response or throws with detail) ──── async function callOllama() { const url = `${OLLAMA_URL}/api/generate` console.log(`[prompts] calling Ollama url=${url} model=${OLLAMA_MODEL}`) const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: OLLAMA_MODEL, prompt: 'Write one creative writing prompt for a young writer aged 10–14. Make it imaginative, specific, and intriguing — a little mysterious or adventurous. Write only the prompt itself: no introduction, no explanation, no quotation marks. Maximum two sentences.', stream: false, }), signal: AbortSignal.timeout(45000), }) if (!r.ok) { const body = await r.text().catch(() => '(no body)') throw new Error(`HTTP ${r.status} — ${body.slice(0, 200)}`) } const data = await r.json() const prompt = data.response?.trim() if (!prompt) throw new Error(`empty response — raw: ${JSON.stringify(data).slice(0, 200)}`) return prompt } // ── Router ─────────────────────────────────────────────────────────────── const router = Router() router.use(auth) router.get('/', async (req, res) => { try { const prompt = await callOllama() console.log(`[prompts] Ollama OK — "${prompt.slice(0, 60)}…"`) res.json({ prompt, source: 'ollama', model: OLLAMA_MODEL }) } catch (err) { console.error(`[prompts] Ollama failed, using built-in fallback. Reason: ${err.message}`) res.json({ prompt: nextFallback(), source: 'local' }) } }) // ── Debug endpoint — hit /api/prompts/test to see exactly what Ollama returns router.get('/test', async (req, res) => { const result = { url: `${OLLAMA_URL}/api/generate`, model: OLLAMA_MODEL } try { result.prompt = await callOllama() result.status = 'ok' } catch (err) { result.status = 'error' result.error = err.message } console.log('[prompts] /test result:', result) res.json(result) }) export default router