import { browser } from "$app/environment";
import { dev } from "$app/environment";

if (browser) {
  for (const v of [
    "debug",
    "log",
    "info",
    "warn",
    "error",
    "trace",
  ] satisfies (keyof typeof console)[]) {
    const old = ((globalThis as any)['_oldconsole_' + v] ?? console[v]) as typeof console[typeof v];
    (globalThis as any)['_oldconsole_' + v] = old;
    console[v] = (a, ...b) => {
      if (typeof a === "string") {
        const tags_unparsed = a.match(/^(\s*\[[\w\s]+\])*/mu)?.[0];
        const pre: string[] = [];
        const styles: string[] = [];
        if (tags_unparsed) {
          let tag_unparsed = null as null | string;
          while ((tag_unparsed = a.match(/^(\s*\[[^\]\r\n]+\])/mu)?.[0])) {
            a = a.substring(tag_unparsed.length);
            tag_unparsed = tag_unparsed.trim();
            let tag = tag_unparsed.substring(1, tag_unparsed.length - 1);
            let colour = "#aa99ffcc";
            switch (tag) {
              case "vite":
                colour =
                  "linear-gradient(-45deg, #41D1FF -50%, #BD34FE 150%)";
                break;
              case "w":
              case "warn":
                colour = "#FFEA83";
                break;
              case "i":
              case "inf":
              case "info":
                colour = "#99AAFF";
                break;
              case "e":
              case "err":
              case "error":
                colour = "#FF99AA";
                break;
              case "success":
              case "succ":
                colour = "#AAFF99";
                break;
              case "motd":
              case "devmotd":
                colour =
                  "linear-gradient(-75deg, #99AAFF -90%, #BD34FE 150%)";
                break;
              case "uwu":
                colour = "#BBAAFF";
                break;
              case 'keystore':
                colour = '#CC99FF';
                break;
              case 'globalState':
                colour = '#E699FF';
                break;
            }
            let baseMainStyles = `
background: ${colour};
color: #1a1a1a;
font-width: bold;
font-family: Inter, sans-serif;
padding-top: 4px;
padding-bottom: 4px;
`
            if (tag.includes('=')) {
              const v = tag.split('=');
              pre.push(`%c${v.shift() ?? ''}: %c${v.join('=')}%c`)
              baseMainStyles += `background: #667;
`
              styles.push(`${baseMainStyles}
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
padding-left: 4px;
color: #3a3a3a;
`, `${baseMainStyles}
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
padding-right: 4px;
margin-right: 4px;
`, '')
            } else {
              pre.push(`%c${tag}%c`);
              styles.push(
                `
${baseMainStyles}
padding-left: 4px;
padding-right: 4px;
border-radius: 4px;
margin-right: 4px;
`,
                "",
              );
            }
          }
        }
        a = `​\n${pre.join("")}${(a as string).trimStart()}`;
        if (b.length) b.push("\n​");
        else a += "\n​";
        return old(a, ...styles, ...b);
      } else return old(a, ...b);
    };
  }

  const s = [
    [`CALL THE FIRE DEPARTMENT, WE JUST NUKED THE BUILDING`],
    [`RIP Terry`],
    [`WARNING, NUKING IS NOW LEGAL... WORLDWIDE!!! >~<`],
    [`Welcome back, Anon`],
    [`when you suckin on her nuts`],
    [`wait.. nuking's actually kinda hot......`],
    [`you know what happens after a nuke? smoke %c#3`, "color: #ff0000;"],
    [`Fucking the industry's transfems since 20xx`],
    [
      `%c"How many Bitcoin?"%c I prefer my coin count in bytes.`,
      "color: #99aaff;",
      "color: undo;",
    ],
    [`Lesbians are hot %c<3`, "color: #ff99aa;"],
    [
      `Astolfo didn't kill %chim%c- herself`,
      "text-decoration: line-through;",
      "text-decoration: none;",
    ],
  ] as [string, ...string[]][];
  const strs = s.map(([v0, ...vn]) => [
    `[${dev ? "dev" : ""}motd]%c${v0}`,
    ...[
      // Base Styles
      `
color: #12488B;
font-family: "Courier New", Courier, monospace;
`,
      // Additional Styles
      ...vn,
    ]
      // Parse Declarations
      .map((_, i, a) =>
        a[i]
          .split(";")
          .filter((v) => v.trim().length !== 0)
          .map((v) => v.split(":"))
          .map(
            ([k, ...v]) =>
              [k.trim(), v.join(":").trim()] as [key: string, value: string],
          ),
      )
      // Inherit from previous values
      .map((_, i, a) => {
        const props = {} as Record<string, string[]>;
        for (let i2 = 0; i2 <= i; i2++) {
          for (const [k, v] of a[i2]) {
            if (v === "undo") (props[k] ?? []).pop();
            else (props[k] = props[k] ?? []).push(v);
          }
        }
        return Object.fromEntries(
          Object.entries(props).map(([k, v]) => [k, v[v.length - 1]]),
        );
      })
      // Join into strings
      .map((v) => {
        return Object.entries(v)
          .map((v) => v.join(": ") + ";")
          .join("\n");
      }),
  ]);
  console.debug(
    ...strs[Math.floor(Math.random() * strs.length)],
  );
}