import { Jam } from "@/types";
import { Server, type Socket } from "socket.io";

import Redis from "ioredis";

// This is terrible, but need to fi
const redis = new Redis(
  "rediss://default:AVyDAAIjcDEzMmFlODZkMjc3YmU0M2VmOGMwOTliYWY1MTQyYzdmY3AxMA@apt-cricket-23683.upstash.io:6379"
);

const io = new Server(8080, { cors: { origin: "*" } });

let clips = [
  {
    id: "01324cd1-6b02-4925-bf93-e0682c3bbe89",
    video_url: "https://cdn1.suno.ai/01324cd1-6b02-4925-bf93-e0682c3bbe89.mp4",
    audio_url: "https://cdn1.suno.ai/01324cd1-6b02-4925-bf93-e0682c3bbe89.mp3",
    image_url:
      "https://cdn2.suno.ai/image_01324cd1-6b02-4925-bf93-e0682c3bbe89.jpeg",
    image_large_url:
      "https://cdn2.suno.ai/image_large_01324cd1-6b02-4925-bf93-e0682c3bbe89.jpeg",
    is_video_pending: false,
    major_model_version: "",
    model_name: "chirp-up-t-0",
    metadata: {
      tags: "Chinese accent, Chinese woman, pop",
      prompt:
        "feel the breeze that's calling me\n golden skies above the sea\n endless summer chasing dreams \nyeah you and i we werere wild and free \n\nwe chillin out just riding the vibe under the stars you by my side it feels so right the night is ours you and me are shooting stars \n\nwe'll never fade the nights into days a summer will'll always stay \n\non the sand dunes we run we fly \nburning bright beneath the moonlit sky \nhold me close don't let this go \n\ndrifting closer side by side feel us fading with the tide \nevery glance every touch \nmakes me feel like it's enough \n\nwe were chillining out just riding the vibe under the stars you by my side feels so right the night is ours you and me i' shooting stars \n\nwe'll never fade the nights into days our summer will always stay \n\non the sand dunes we run we fly \nbuilding bright beneath the moonlit sky every come don let this go \nthe d on the sand dunes we'll be writing our story \n\nevery moment is a memory of glory on the sand dun run we fly \nwhen the winds blow in we sway we sway to the shifting sands we sway we sway \n\nwe'll never fade the nights and the days a summer will always stay the moonit sky hearts \ndon't let this go on the sand dun well be writing our story every moment is a memory of glory on the sand dun above we fly on dun",
      type: "upsample",
      duration: 159.48,
      refund_credits: false,
      stream: false,
      has_vocal: true,
      upsample_clip_id: "d6d25b99-4b1c-4a6a-82f4-56cd644140f2",
      task: "upsample",
    },
    display_name: "Tony",
    handle: "tony",
    is_handle_updated: true,
    avatar_image_url: "https://cdn1.suno.ai/de97d32b.webp",
    user_id: "9071a851-c987-4c58-9740-b03cb1cbdd7b",
    created_at: "2024-11-01T20:11:58.766Z",
    status: "complete",
    title: " (Remastered)",
    play_count: 0,
    upvote_count: 0,
    is_public: false,
    submitterId: 248,
    submitterUsername: "RoRoTuck",
    url: "",
  },

  {
    id: "535cc92b-8355-4168-9513-8c01394c6767",
    video_url: "https://cdn1.suno.ai/535cc92b-8355-4168-9513-8c01394c6767.mp4",
    audio_url: "https://cdn1.suno.ai/535cc92b-8355-4168-9513-8c01394c6767.mp3",
    image_url:
      "https://cdn2.suno.ai/image_535cc92b-8355-4168-9513-8c01394c6767.jpeg",
    image_large_url:
      "https://cdn2.suno.ai/image_large_535cc92b-8355-4168-9513-8c01394c6767.jpeg",
    is_video_pending: false,
    major_model_version: "v3",
    model_name: "chirp-v3",
    metadata: {
      tags: "afrobeat, japanese jazz",
      prompt:
        "[Verse]\nCity streets glowing bright\nNeon dreams in the night\nDancing shadows on the run\nChasing stars one by one\n\n[Verse 2]\nElectric whispers all around\nLost in colors never found\nFlashing signs that call my name\nIn this city’s endless game\n\n[Chorus]\nNeon lights guide our way\nTurn the night into day\nIn the glow we find our truth\nEndless magic chasing youth\n\n[Verse 3]\nMoonlit skies painted bold\nStories in neon told\nHeartbeats race to the beat\nIn the glow our lives meet\n\n[Bridge]\nBeneath the signs we find our beat\nIn neon hues we feel complete\nWhile the city hums its song\nTogether we belong\n\n[Chorus]\nNeon lights guide our way\nTurn the night into day\nIn the glow we find our truth\nEndless magic chasing youth",
      type: "gen",
      duration: 191,
      refund_credits: false,
      stream: true,
    },
    display_name: "MACH 🚀",
    handle: "mac",
    is_handle_updated: true,
    avatar_image_url: "https://cdn1.suno.ai/defaultPink.webp",
    user_id: "42b093e8-5f16-4c77-8953-a9dc6e312d11",
    created_at: "2024-11-01T20:22:11.355Z",
    status: "complete",
    title: "Neon Dreams",
    play_count: 1,
    upvote_count: 0,
    is_public: false,
    submitterId: 243,
    submitterUsername: "martin",
    url: "",
  },
  {
    id: "de3b4c65-6303-47f1-9384-dc2c31e169ff",
    video_url: "https://cdn1.suno.ai/de3b4c65-6303-47f1-9384-dc2c31e169ff.mp4",
    audio_url: "https://cdn1.suno.ai/de3b4c65-6303-47f1-9384-dc2c31e169ff.mp3",
    image_url:
      "https://cdn2.suno.ai/image_de3b4c65-6303-47f1-9384-dc2c31e169ff.jpeg",
    image_large_url:
      "https://cdn2.suno.ai/image_large_de3b4c65-6303-47f1-9384-dc2c31e169ff.jpeg",
    is_video_pending: false,
    major_model_version: "v3",
    model_name: "chirp-v3",
    metadata: {
      tags: "hard hitting hip hop, maximum bass, party in the club",
      prompt:
        "Verse 1:\nBroken elevators, pissy hallways\nSirens every night, that's how my block stays\nHeat don't work in winter, rats in the walls\nMama working doubles, I can hear her footsteps in the halls\nNo lights in the stairwell, moving in the dark\nProject windows facing other projects like a work of art\nSeven deep in a two-bedroom, we make it work though\nLearning mathematics off them sandwich bags, that's word though\n\nHook:\nAin't no silver spoons up in the bricks (nah)\nJust empty fridges making stomachs sick (yeah)\nThey say pull yourself up, make it flip (what)\nBut they ain't never lived a life like this (never)\n\nVerse 2:\nGovernment cheese and them food stamp dreams\nWater dripping from the ceiling when it rains, know what I mean?\nGrandma holding down three generations in this spot\nTeaching us to survive with what little that we got\nYoung boys on them corners, trying to find their way\nOld heads on them benches reminiscing better days\nThey tore down building 4, said they'd build it back\nFive years later, still a empty lot of crack\n\n(Repeat Hook)\n\nBridge:\nThey don't understand this life\nThey don't feel this pain\nProject hallways raised us\nConcrete in our veins",
      type: "gen",
      duration: 216.24,
      refund_credits: false,
      stream: true,
    },
    display_name: "Stev",
    handle: "stevstev",
    is_handle_updated: true,
    avatar_image_url: "https://cdn1.suno.ai/defaultBlue.webp",
    user_id: "85e4822f-0081-428b-a514-fac424aac069",
    created_at: "2024-11-01T20:22:47.503Z",
    status: "complete",
    title: "my rap song",
    play_count: 1,
    upvote_count: 0,
    is_public: false,
    submitterId: 254,
    submitterUsername: "stev - this sounds like action bronson",
    url: "",
  },
  {
    id: "d99f0c8c-9a15-4217-bcc3-cf9bda983657",
    video_url: "https://cdn1.suno.ai/d99f0c8c-9a15-4217-bcc3-cf9bda983657.mp4",
    audio_url: "https://cdn1.suno.ai/d99f0c8c-9a15-4217-bcc3-cf9bda983657.mp3",
    image_url:
      "https://cdn2.suno.ai/image_d99f0c8c-9a15-4217-bcc3-cf9bda983657.jpeg",
    image_large_url:
      "https://cdn2.suno.ai/image_large_d99f0c8c-9a15-4217-bcc3-cf9bda983657.jpeg",
    is_video_pending: false,
    major_model_version: "v3",
    model_name: "chirp-v3",
    metadata: {
      tags: "gritty aggressive hardcore rap",
      prompt:
        "[Verse]\nSpit venom, infiltrate your thoughts and bend 'em\nIf I told you roundly, \"Thin is in,\" then you would spend\nyour last dime to have the right segment\nWhen MTV promotes a trend, you rush to get in it\nWomen, go through the doors you got to fit in\nBig corporations tell you what's a hit or miss\nIf or not, you don't even know what the 'gist of this is\n\n[Verse 2]\nGovernors who held the most 'power,' influenced us\nThem with no interest with, open fist, then tumors just\nGrew runnin' ruthless, for filled with no sense of\nDuty honor, to no man but themselves, yes\nPeople, a few shipped from multiple sire lynching\nWhether, the media was a conglomerate or a benched in\nA minor aspect, for the owners also-minded strands\nof in the country in which I strive\n\n[Chorus]\nGrand Poobah's playin' God over the mass\nUpholding unnaturals means as upper class\nThis phenomenon, of an innocent,\nattitude that has to be sent\n[Chorus]\nWhen I say critical sit, your left to find it, bad\nWith no measuring stick, to the times we had\nTo lie didn't arrive yet, the longest time, the fiber had\nCouldn't think for yourself\nSubjugated by his\n-Render emphatic, love every part of from\nthe start which is sent.\n",
      type: "gen",
      duration: 88.6,
      refund_credits: false,
      stream: true,
    },
    display_name: "RestrainedStaff0309",
    handle: "nnnnnnnnnn",
    is_handle_updated: true,
    avatar_image_url: "https://cdn1.suno.ai/defaultBlue.webp",
    user_id: "ec1c274a-e3ca-4abb-8140-eccd418cbbf3",
    created_at: "2024-11-01T20:25:41.195Z",
    status: "complete",
    title: "overlord",
    play_count: 2,
    upvote_count: 0,
    is_public: false,
    submitterId: 258,
    submitterUsername: "Nat",
    url: "",
  },
  {
    id: "0f971b1f-e700-4ab1-9a7f-d836e15035be",
    video_url: "https://cdn1.suno.ai/0f971b1f-e700-4ab1-9a7f-d836e15035be.mp4",
    audio_url: "https://cdn1.suno.ai/0f971b1f-e700-4ab1-9a7f-d836e15035be.mp3",
    image_url:
      "https://cdn2.suno.ai/image_0f971b1f-e700-4ab1-9a7f-d836e15035be.jpeg",
    image_large_url:
      "https://cdn2.suno.ai/image_large_0f971b1f-e700-4ab1-9a7f-d836e15035be.jpeg",
    is_video_pending: false,
    major_model_version: "v3",
    model_name: "chirp-v3",
    metadata: {
      tags: "hard hitting hip hop, maximum bass, party in the club",
      prompt:
        "Verse 1:\nBroken elevators, pissy hallways\nSirens every night, that's how my block stays\nHeat don't work in winter, rats in the walls\nMama working doubles, I can hear her footsteps in the halls\nNo lights in the stairwell, moving in the dark\nProject windows facing other projects like a work of art\nSeven deep in a two-bedroom, we make it work though\nLearning mathematics off them sandwich bags, that's word though\n\nHook:\nAin't no silver spoons up in the bricks (nah)\nJust empty fridges making stomachs sick (yeah)\nThey say pull yourself up, make it flip (what)\nBut they ain't never lived a life like this (never)\n\nVerse 2:\nGovernment cheese and them food stamp dreams\nWater dripping from the ceiling when it rains, know what I mean?\nGrandma holding down three generations in this spot\nTeaching us to survive with what little that we got\nYoung boys on them corners, trying to find their way\nOld heads on them benches reminiscing better days\nThey tore down building 4, said they'd build it back\nFive years later, still a empty lot of crack\n\n(Repeat Hook)\n\nBridge:\nThey don't understand this life\nThey don't feel this pain\nProject hallways raised us\nConcrete in our veins",
      type: "gen",
      duration: 168.44,
      refund_credits: false,
      stream: true,
    },
    display_name: "Stev",
    handle: "stevstev",
    is_handle_updated: true,
    avatar_image_url: "https://cdn1.suno.ai/defaultBlue.webp",
    user_id: "85e4822f-0081-428b-a514-fac424aac069",
    created_at: "2024-11-01T20:22:47.502Z",
    status: "complete",
    title: "my rap song",
    play_count: 2,
    upvote_count: 0,
    is_public: false,
    submitterId: 254,
    submitterUsername: "stev - this sounds like nas?",
    url: "",
  },
  {
    id: "16808868-8b81-49df-8052-d8192604704e",
    video_url: "https://cdn1.suno.ai/16808868-8b81-49df-8052-d8192604704e.mp4",
    audio_url: "https://cdn1.suno.ai/16808868-8b81-49df-8052-d8192604704e.mp3",
    image_url:
      "https://cdn2.suno.ai/image_16808868-8b81-49df-8052-d8192604704e.jpeg",
    image_large_url:
      "https://cdn2.suno.ai/image_large_16808868-8b81-49df-8052-d8192604704e.jpeg",
    is_video_pending: false,
    major_model_version: "v3",
    model_name: "chirp-v3",
    metadata: {
      tags: "wobbly bass, wobble wobble wobble",
      prompt:
        "[Verse]\nSo I look in your eyes\nI thought it was gonna be fine\nBut I locked up your system\nGirl\n\n[Verse]\nAnd when you’re close\nI get the most\nAnd now I’m staring at a ghost\nAnd now I don’t know what to do\n\n[Chorus]\nCuz now she’s all laggy\nI swear to god I didn’t mean to\nI keep on asking her\nBut now it just hurts to see you\nAnd I don’t know what to do\nCuz now you’re all— all blue",
      type: "gen",
      duration: 151.96,
      refund_credits: false,
      stream: true,
    },
    display_name: "whatroughbeats",
    handle: "pat",
    is_handle_updated: true,
    avatar_image_url: "https://cdn1.suno.ai/1aad21b2.webp",
    user_id: "22f84ba7-c8bc-4d5e-9ff9-9ea90f2870a8",
    created_at: "2024-11-01T20:21:49.444Z",
    status: "complete",
    title: "Midnight Waffle House",
    play_count: 4,
    upvote_count: 0,
    is_public: false,
    submitterId: 268,
    submitterUsername: "patric.io",
    url: "",
  },
  {
    id: "db5f0b0e-5684-47ff-9273-e2411ba4407f",
    video_url: "https://cdn1.suno.ai/db5f0b0e-5684-47ff-9273-e2411ba4407f.mp4",
    audio_url: "https://cdn1.suno.ai/db5f0b0e-5684-47ff-9273-e2411ba4407f.mp3",
    image_url:
      "https://cdn2.suno.ai/image_db5f0b0e-5684-47ff-9273-e2411ba4407f.jpeg",
    image_large_url:
      "https://cdn2.suno.ai/image_large_db5f0b0e-5684-47ff-9273-e2411ba4407f.jpeg",
    is_video_pending: false,
    major_model_version: "v3",
    model_name: "chirp-v3",
    metadata: {
      tags: "rap, adlibs, energy, DEEP LOW voice, starts off acapalle then beat builds up and 808s drop. male voice., trap, hip hop",
      prompt:
        "[Verse]\nuh... uh... uh UH UHHHHH\nNuh nuh no no November ya yuh\nThis shit ain't no November ya yuh yuh\nCatch me with shorts in the winter(short shorts)\nthis shit ain't no November yuh yuh yuhhhh\n\n[Verse 2]\nPolar bears on the edge of a block yuh\nOur planet warming up nonstop yuh\nWe cooked now ain't no takin' stock yuh\nHurricanes whirl and the ice is pop yuh\n\n[Chorus]\nThis world is burnin' can't you see\nHeat comin' down on you and me\nGlaciers melt and waters rise\nNo more whispers hear the cries\n\n[Bridge]\nEvery day hotter than before\nForests turn to deserts more\nSmog in the air choakin' lungs\nNature's song left unsung\n\n[Verse 3]\nRivers dryin' animals dyin' yuh\nFires blazin' ain't no lyin' yuh\nFeel the sweat drip off my brow yuh\nHell on Earth feel it now yuh\n\n[Chorus]\nThis world is burnin' can't you see\nHeat comin' down on you and me\nGlaciers melt and waters rise\nNo more whispers hear the cries",
      type: "gen",
      duration: 240.64,
      refund_credits: false,
      stream: true,
    },
    display_name: "bass",
    handle: "bbassel",
    is_handle_updated: true,
    avatar_image_url: "https://cdn1.suno.ai/60a3d937.webp",
    user_id: "dd821e70-82ac-40f3-a1fb-e56946b30599",
    created_at: "2024-11-01T20:30:07.029Z",
    status: "complete",
    title: "Nuh No November",
    play_count: 2,
    upvote_count: 0,
    is_public: false,
    submitterId: 267,
    submitterUsername: "Bassel",
    url: "",
  },
  {
    id: "0c9c67c9-59cb-4e9d-9ef9-f1d70b1b4475",
    video_url: "https://cdn1.suno.ai/0c9c67c9-59cb-4e9d-9ef9-f1d70b1b4475.mp4",
    audio_url: "https://cdn1.suno.ai/0c9c67c9-59cb-4e9d-9ef9-f1d70b1b4475.mp3",
    image_url:
      "https://cdn2.suno.ai/image_0c9c67c9-59cb-4e9d-9ef9-f1d70b1b4475.jpeg",
    image_large_url:
      "https://cdn2.suno.ai/image_large_0c9c67c9-59cb-4e9d-9ef9-f1d70b1b4475.jpeg",
    is_video_pending: false,
    major_model_version: "v3.5",
    model_name: "chirp-v3.5",
    metadata: {
      tags: "chicago rap, soulful, [chipmunk sample]",
      prompt:
        "[organ intro with echoing reverb]\n\n[chipmunk sample]\nShe’s the shadow in the room when I’m alone,\nA ghost I keep on callin’ my own,\nNot love, just a symbol, this aching I hold,\nIn her eyes, I see my soul turnin’ cold.\n\n[Verse 1]\nShe’s the quiet at the end of a call, the empty ring,\nA habit I keep just to feel somethin' cling,\nNot here to heal me, only here to remind,\nLoneliness wears her face in my mind.\n\nEvery glance is a mirror, a vision of loss,\nEach word, a reminder of the lines I crossed,\nShe’s a place I return to just to feel whole,\nAn echo that haunts but can’t fill the hole.\n\n[chipmunk sample]\nShe’s the shadow in the room when I’m alone,\nA ghost I keep on callin’ my own,\nNot love, just a symbol, this aching I hold,\nIn her eyes, I see my soul turnin’ cold.\n\n[Verse 2]\nI call her name like it’s comfort, like it’s home,\nBut her silence just thickens the walls of stone,\nShe’s not a woman, she’s a weight on my chest,\nA phantom of comfort, denying me rest.\n\nIn every smile, there’s a sliver of pain,\nIn every touch, it’s a void I can’t name,\nI hold her close but drift further away,\nChasin' the warmth in her cold embrace.",
      type: "gen",
      duration: 158,
      refund_credits: false,
      stream: true,
      has_vocal: false,
      artist_clip_id: "9458e83f-7733-4e59-95d6-82b801de6d49",
      persona_id: "e850b426-f9f2-482f-9c03-744f124d40c2",
      task: "artist_consistency",
    },
    display_name: "ali from suno emails",
    handle: "kant",
    is_handle_updated: true,
    avatar_image_url: "https://cdn1.suno.ai/8cd2c755.webp",
    user_id: "f977b85f-4022-4f4c-9718-fc0d520c797d",
    created_at: "2024-11-01T20:22:52.154Z",
    status: "complete",
    title: "v4444",
    play_count: 10,
    upvote_count: 1,
    is_public: false,
    submitterId: 264,
    submitterUsername: "ali",
    url: "",
  },
];

let jam: Jam = {
  id: "test",
  name: "Spin Sync",
  rooms: {
    test: {
      id: "1",
      name: "Room 1",
      clips: clips,
      playState: null,
    },
  },
  presence: {},
};

let loadedData = false;

const bootstrap = async () => {
  const loadData = async () => {
    const existingJam = await redis.get("jam-test");
    if (existingJam) {
      jam.rooms = JSON.parse(existingJam);
    } else {
      await redis.set("jam-test", JSON.stringify(jam.rooms));
    }
    loadedData = true;
    io.sockets.emit("snapshot", jam);
    setInterval(async () => {
      await redis.set("jam-test", JSON.stringify(jam.rooms));
      console.log("Flushed jam rooms to Redis");
    }, 30000);
  };
  loadData();

  io.on("connection", (socket: Socket) => {
    console.log("New user connected:", socket.id);

    jam.presence[socket.id] = {
      id: socket.id,
      username: "Anon",
    };

    if (loadedData) {
      socket.emit("snapshot", jam);
    }

    io.sockets.emit("presence", jam.presence);

    socket.on("presence-set-username", ({ username }) => {
      if (!jam.presence[socket.id]) {
        jam.presence[socket.id] = {
          id: socket.id,
          username,
        };
      }
      jam.presence[socket.id].username = username;

      io.sockets.emit("presence", jam.presence);
    });

    socket.on("reaction", (event) => {
      console.log("new reaction", event);
      socket.volatile.broadcast.emit("reaction", { id: socket.id, ...event });
    });

    socket.on("play-state", (event) => {
      console.log("play-state", event);

      jam.rooms["test"].playState = event;
      io.sockets.emit("play-state", { id: socket.id, ...event });
    });

    socket.on("add-clip", (clip) => {
      jam.rooms["test"].clips.push(clip);
      io.sockets.emit("add-clip", clip);
    });

    socket.on("disconnect", () => {
      console.log("User disconnected:", socket.id);
      delete jam.presence[socket.id];
      io.sockets.emit("presence", jam.presence);
    });
  });
};

bootstrap();
