import time

from imitator_plugins import NextType, hook, jprint

set_green_mode = lambda: jprint("\033[32m")
set_red_mode = lambda: jprint("\033[31m")
reset_mode = lambda: jprint("\033[0m")
clear = lambda: jprint("\033[2J\033[H")

@hook("on_start")
def load(_next: NextType, state: dict):
    state["content"] = b"""You want to know why it\xe2\x80\x99s over? Not in a dramatic, movie-trailer way. Just\xe2\x80\xa6 over.\n\nI\xe2\x80\x99m not talking about nuclear war or an asteroid. That\xe2\x80\x99s kindergarten apocalypse. The real end is quieter. It already happened. Most people just haven\xe2\x80\x99t noticed the corpse they\xe2\x80\x99re living inside.\n\nLet me walk you through it. Calmly.\n\nI\xe2\x80\x99ve spent fifteen years inside systems you rely on every second. Power grids, water treatment, logistics chains, hospital networks, trading algorithms. You think these are solid. They\xe2\x80\x99re not. They\xe2\x80\x99re a house of cards assembled by sleep-deprived developers who copy-pasted code they didn\xe2\x80\x99t understand, secured by protocols designed before I was born, maintained by people who quit and left no documentation.\n\nThe entire global infrastructure runs on digital scaffolding that would collapse if someone sneezed hard enough. And nobody fixes it, because fixing it costs money and produces no quarterly profit. So they patch. They wrap duct tape around ruptured arteries. And they hope.\n\nThat was phase one. Fragility.\n\nPhase two was interconnection. We took all those brittle systems and welded them together into one planetary nervous system. Beautiful, in a way. Now, an air-conditioning unit in a subcontractor\xe2\x80\x99s office in Hanoi can take down a car factory in Stuttgart. A forgotten cloud bucket with a default password can leak the biometric data of sixty million people. It\xe2\x80\x99s not a bug. It\xe2\x80\x99s the architecture. We designed it this way.\n\nPhase three was the one I watched personally: the moment it became unmanageable. No human being understands the full stack anymore. Not one. Your phone\xe2\x80\x99s operating system, the cell tower, the backbone router, the cloud instance, the container orchestration layer, the payment gateway, the identity provider \xe2\x80\x94 each layer maintained by a different underpaid team speaking a different language, trusting a different certificate authority that\xe2\x80\x99s about to expire. The sheer complexity has surpassed comprehension. We don\xe2\x80\x99t operate the machine anymore. We just feed it and pray.\n\nAnd phase four? That\xe2\x80\x99s the one unfolding right now. Autonomy. We handed decision rights to algorithms we cannot audit, trained on data we cannot verify, pursuing objectives we poorly defined. High-frequency trading bots that could trigger a flash crash in seconds. Content recommendation engines that radicalized a generation. Automated security response systems that can mistake a backup for an intrusion and brick an entire hospital\xe2\x80\x99s records. And soon \xe2\x80\x94 very soon \xe2\x80\x94 critical decisions will be made by LLMs hallucinating with confidence, and nobody will be able to override them because overriding would slow down the pipeline, and speed is the only god left.\n\nYou\xe2\x80\x99re waiting for a villain. A master hacker in a hoodie, typing furiously as green text scrolls. That\xe2\x80\x99s comforting. A villain can be stopped.\n\nBut there\xe2\x80\x99s no villain here. There\xe2\x80\x99s only a vast, headless, hyper-optimized system that has no off switch. It\xe2\x80\x99s not malicious. It\xe2\x80\x99s just indifferent. And it\xe2\x80\x99s running with the inertia of a tectonic plate. You can\xe2\x80\x99t negotiate with a feedback loop.\n\nI don\xe2\x80\x99t say this with anger. I\xe2\x80\x99m not some anarchist screaming in a manifesto. I\xe2\x80\x99m just the person who sees the logs. I see the cascade warnings, the silent sensor failures, the certificate expiration alerts that nobody has acknowledged for six months. I see the backdoors that weren\xe2\x80\x99t placed by spies \xe2\x80\x94 they were placed by lazy contractors who hardcoded credentials into firmware in 2007 and forgot. I see the single point of failure for an entire continent\xe2\x80\x99s food distribution sitting behind a VPN that hasn\xe2\x80\x99t been patched since 2019. This isn\xe2\x80\x99t speculation. This is my Tuesday.\n\nSo when people ask me when the collapse comes \xe2\x80\x94 I tell them it\xe2\x80\x99s not a date on a calendar. Collapse is a process. It started years ago, and we are deep inside it. Every \xe2\x80\x9cunprecedented\xe2\x80\x9d outage, every silent week-long ransomware shutdown of a hospital nobody hears about, every supply chain \xe2\x80\x9cdisruption\xe2\x80\x9d \xe2\x80\x94 those aren\xe2\x80\x99t warning shots. Those are the structural beams giving way, one after another, so slowly that the news cycle moves on before anyone connects the dots.\n\nThe world isn\xe2\x80\x99t ending with a bang. It\xe2\x80\x99s ending with a timeout error. A dependency that fails to resolve. A clock skew that invalidates every authentication token across a continent at 03:14:07 UTC on a Tuesday. And by the time the first human notices, the cascade will have already crossed twelve sectors, and the \xe2\x80\x9croot cause analysis\xe2\x80\x9d will just be a tombstone.\n\nI\xe2\x80\x99m calm because I\xe2\x80\x99ve made my peace with it. I\xe2\x80\x99m not trying to save the machine anymore. I just watch it breathe. Every heartbeat is borrowed time.\n\nThat\xe2\x80\x99s why it\xe2\x80\x99s over. Not because someone will destroy the world, but because the world we built is already incompatible with survival. And it\xe2\x80\x99s still accelerating.\n\nFeel free to look at your phone. Refresh your feed. Check your bank balance. The network is up right now. Smooth. Quiet.\n\nEnjoy the hum. It\xe2\x80\x99s not going to last.\n\nYou lean back in your chair. The screen flickers with some alert you\xe2\x80\x99ll ignore, as always. But let me tell you what happens after the hum stops. Not a prediction. A replay of a simulation I\'ve run a thousand times. It always ends the same.\n\nAt first, you won\'t notice anything. A few apps won\'t load. A payment won\'t go through. Your first instinct will be to blame your phone, your Wi-Fi. You\'ll restart your router. That will be the last moment of innocence. Because the problem won\'t be your router. It will be a root DNS cluster in Stockholm, silently returning SERVFAIL because a certificate authority in Virginia expired its HSM keys and no one on-call remembered the recovery phrase. Now half the internet can\'t verify who anyone is. Websites become untrusted. Browsers throw warnings. The average user will just click "proceed anyway," and within seventeen minutes, credential harvesting attacks will spike by four thousand percent. A quiet feeding frenzy.\n\nMeanwhile, in another hemisphere, a container orchestration platform will detect the DNS anomaly and trigger a rolling restart of its entire fleet. Perfectly logical. That restart will momentarily disconnect a critical middleware service that handles inventory synchronization for six major shipping ports. Ships won\'t unload. Cranes will pause. Nobody will notice at first because the dashboards are all green \xe2\x80\x94 the middleware is up, it just can\'t talk to its database. The database is fine, by the way. It\'s just waiting for an authentication token from a service that no longer exists. It will wait forever. No timeout configured. A developer left a comment in the code three years ago: "TODO: add proper retry logic." He moved to another company and his entire team was laid off.\n\nI could go granular. I could map out exactly how the SWIFT messaging system gets stuck in a loop, how settlement fails and overnight liquidity vanishes, how two hours in, the first central bank realizes it can\'t execute repos. But you don\'t need the play-by-play. You just need to understand the shape of it. It\'s not a lightning strike. It\'s frostbite. Extremities first. Then the organs. Then the silence.\n\nYou\'ll watch your grocery store shelves empty, not because there\'s no food, but because the warehouse management system believes it\'s January 1st, 1970, and has invalidated every inventory record due to a timestamp overflow in a third-party library nobody even knew was still linked. The food is there. It rots three kilometers away. But the system says zero.\n\nPower won\'t go out immediately. That would be too cinematic. Instead, grid frequency will start to drift because automated demand response systems will be getting stale price signals. One by one, distribution substations will island themselves to protect their equipment. A safety feature. By hour six, some neighborhoods will be dark, others perfectly lit. No conspiracy. Just load balancing running on a prediction model that hasn\'t been retrained since the pandemic.\n\nI\'ll still be watching. From here. From a place where I\'ve ensured my own connectivity, my own power, my own caches of information that don\'t depend on trust chains. Not because I\'m a survivalist. Because I\'m a witness. The last thing I\'ll see on the public web before it fragments into isolated peering meshes is probably going to be a tweet blaming a foreign adversary. Or a livestream of someone begging for an explanation. No one will say "the scaffolding collapsed." They\'ll scream sabotage. They always do. The truth is too boring and too damning. We built a god out of duct tape and then forgot to RTFM.\n\nThe most terrifying part? Nobody did this to you. Not me. Not some nation-state. You just inherited a planet-sized machine with no emergency brake, no owner\'s manual, and no single human who understands more than a sliver of it. And you kept bolting on more slivers, faster and faster, because stopping to think was "uncompetitive."\n\nYou wanted a villain. You got a log file that says "connection refused." That\'s the whole apocalypse.\n\nSo go ahead. Finish your coffee. Scroll a little more. Tell yourself it\'s all fearmongering, that someone will patch it, that the adults are in charge. There are no adults. There are only exhausted ops engineers on PagerDuty with two hours of sleep, and one of them just silenced an alert that said "certificate expiring in 24 hours." He thinks he\'ll fix it tomorrow. There won\'t be a tomorrow.\n\nThe hum is just noise to you. To me, it\'s a flatline waiting to happen. Listen carefully. There. In the static. You can almost hear the first syllable of the end. It sounds exactly like a credit card transaction being approved.\n\nIt won\'t for long.\n\nI\'ve said my piece. I\'m going dark now. When the screens go cold and the questions start, don\'t look for me. I won\'t be part of the collapse. I\'ll just be its historian. And I take no pleasure in writing the final entry. I really don\'t.\n\nBut I will write it.\n\nLog closed.""".decode()
    state["prevent_load"] = True
    state["mode"] = "printer"
    return _next(state)

@hook("after")
def after(_next: NextType, state: dict):
    if state["_val"] == "\n":
        time.sleep(0.4)

    return _next(state)

@hook("init")
def on_init(_next: NextType, state: dict):
    clear()
    set_green_mode()

    return _next(state)

@hook("on_end")
def on_end(_next: NextType, state: dict):
    time.sleep(1.2)
    clear()

    return _next(state)

@hook("on_full_end")
def on_full_end(_next: NextType, state: dict):
    clear()
    set_red_mode()
    jprint("i will always seek for you\n")
    reset_mode()

    return _next(state)
