# retoor <retoor@molodetz.nl>

from .._shared import endpoint, field

CROP_KEYS = [
    "shell",
    "python",
    "webapp",
    "api",
    "rust",
    "haskell",
    "kernel",
    "distsys",
    "mlpipe",
    "secfort",
]
PERK_KEYS = ["yield", "growth", "discount", "xp"]
QUEST_KINDS = ["plant", "harvest", "water", "earn"]
QUEST_SCOPES = ["daily", "weekly"]
LEGACY_KEYS = ["autoharvest", "multiplier", "speed", "plots", "defense", "carryover"]
MASTERY_KEYS = ["autoreplant", "analytics", "contracts"]
INFRA_KEYS = ["registry", "canary", "observability"]
COSMETIC_KEYS = ["title_architect", "title_refactorer", "title_kernel_hacker", "skin_neon"]
BOARD_KEYS = ["score", "prestige", "harvests", "raids", "time_to_kernel", "fair_play", "era"]

GROUP = {
        "slug": "game",
        "title": "Code Farm",
        "intro": """
# Code Farm

The Code Farm is a cooperative idle game. Each member owns a farm of plots, plants software
projects that build over real time, harvests them for coins and XP, upgrades their CI tier for
faster builds, and waters other members' growing builds to speed them up and earn coins.

Refactoring (prestige) costs a dynamic coin fee that grows with prestige and current wealth;
the fees fill a community treasury from which active low-balance farms can claim a weekly grant.

All endpoints negotiate HTML or JSON. POST bodies are form encoded
(`application/x-www-form-urlencoded`). Every own-farm action returns `{"ok": true, "farm": {...}}`
- the full updated farm state - so a client can refresh without a second request; the two
neighbour actions (water, steal) return the neighbour's farm as `{"farm": {...}}`, and a
successful steal adds `stole_coins`. An invalid action (not enough coins, wrong plot state, a
protected harvest, an active cooldown) returns HTTP 400 as
`{"error": {"status": 400, "message": "..."}}`; an unknown farm username is 404. Reading your
own farm state also runs lazy owner effects: the CI Bot legacy upgrade auto-harvests ready
builds, and any due Defense upkeep is charged. The complete rules, formulas, and an automated
client are on the [Code Farm guide](/docs/code-farm.html).
""",
        "endpoints": [
            endpoint(
                id="game-home",
                method="GET",
                path="/game",
                title="Code Farm page",
                summary="The player's own farm: HUD, plot grid, shop, and leaderboard.",
                auth="user",
                negotiation=True,
                sample_response={"ok": True, "farm": {"coins": 50, "level": 1, "plots": []}},
            ),
            endpoint(
                id="game-state",
                method="GET",
                path="/game/state",
                title="Farm state",
                summary="The signed-in player's full farm state as JSON. Reading it auto-collects ready builds (with the CI Bot legacy upgrade, reported as auto_harvested/auto_harvest_coins/auto_harvest_xp) and charges any due Defense upkeep.",
                auth="user",
                sample_response={
                    "ok": True,
                    "farm": {
                        "coins": 50,
                        "level": 1,
                        "ci_tier": 1,
                        "plot_count": 4,
                        "prestige": 0,
                        "stars": 0,
                        "refactor_cost": 20000,
                        "plots": [{"slot": 0, "state": "empty", "raided_fraction": 0.0}],
                        "daily_streak_reset": False,
                        "contract_boost_seconds_remaining": 0,
                        "auto_harvested": 0,
                        "steal_max_per_victim_per_day": 3,
                        "defense_downgrade_available": False,
                        "crops": [
                            {
                                "key": "python",
                                "name": "Python Script",
                                "cost": 15,
                                "reward_coins": 36,
                                "grow_seconds": 120,
                                "locked": False,
                                "market_state": "normal",
                            }
                        ],
                    },
                },
            ),
            endpoint(
                id="game-leaderboard",
                method="GET",
                path="/game/leaderboard",
                title="Farm leaderboard",
                summary="Top 25 farmers on a chosen board: score (default), prestige, harvests (this week), raids (avg coins per successful raid over 30 days, min 3 raids), time_to_kernel, fair_play, or era (current Era only, empty when none is running). Cached about 15 seconds.",
                auth="public",
                params=[
                    field(
                        "board",
                        "query",
                        "string",
                        False,
                        "score",
                        "Leaderboard board key.",
                        options=BOARD_KEYS,
                    )
                ],
                sample_response={
                    "entries": [
                        {
                            "rank": 1,
                            "username": "alice",
                            "level": 4,
                            "xp": 600,
                            "coins": 240,
                            "total_harvests": 52,
                            "prestige": 1,
                            "score": 6120,
                            "title": "The Architect",
                        }
                    ]
                },
            ),
            endpoint(
                id="game-view-farm",
                method="GET",
                path="/game/farm/{username}",
                title="View a farm",
                summary="Another player's farm, with per-plot can_water/can_steal flags computed for the viewer.",
                auth="public",
                negotiation=True,
                params=[field("username", "path", "string", True, "alice", "Farm owner's username.")],
                sample_response={"farm": {"owner_username": "alice", "is_owner": False, "plots": []}},
            ),
            endpoint(
                id="game-plant",
                method="POST",
                path="/game/plant",
                title="Plant a crop",
                summary="Plant a crop in an empty plot. Costs the crop's live coin price (the cost field in the farm state's crops list).",
                auth="user",
                params=[
                    field("slot", "form", "integer", True, "0", "Plot slot index, 0-based."),
                    field("crop", "form", "string", True, "python", "Crop key.", options=CROP_KEYS),
                ],
                sample_response={"ok": True, "farm": {"coins": 35}},
            ),
            endpoint(
                id="game-harvest",
                method="POST",
                path="/game/harvest",
                title="Harvest a build",
                summary="Harvest a finished (state ready) build for coins and XP.",
                auth="user",
                params=[field("slot", "form", "integer", True, "0", "Plot slot index, 0-based.")],
                sample_response={"ok": True, "farm": {"coins": 86}},
            ),
            endpoint(
                id="game-buy-plot",
                method="POST",
                path="/game/buy-plot",
                title="Buy a plot",
                summary="Unlock a new plot (up to 12). Cost starts at 100 coins and doubles per extra plot; the exact price is the farm state's next_plot_cost.",
                auth="user",
                sample_response={"ok": True, "farm": {"plot_count": 5}},
            ),
            endpoint(
                id="game-upgrade",
                method="POST",
                path="/game/upgrade",
                title="Upgrade CI",
                summary="Upgrade the farm CI tier for faster builds (up to tier 5); the exact price is the farm state's ci_next_cost.",
                auth="user",
                sample_response={"ok": True, "farm": {"ci_tier": 2}},
            ),
            endpoint(
                id="game-water",
                method="POST",
                path="/game/farm/{username}/water",
                title="Water a build",
                summary="Water another player's growing build to cut 8% off its build time; pays the visitor 6 coins scaled by their own prestige and Tech Debt Payoff multiplier, plus 3 XP. Once per visitor per build, 3 waterings per build total.",
                auth="user",
                params=[
                    field("username", "path", "string", True, "alice", "Farm owner's username."),
                    field("slot", "form", "integer", True, "0", "Plot slot index, 0-based."),
                ],
                sample_response={"farm": {"owner_username": "alice"}},
            ),
            endpoint(
                id="game-steal",
                method="POST",
                path="/game/farm/{username}/steal",
                title="Steal a build",
                summary="Raid another player's ready build once its protection window has passed. You take a share of the build's realized coin value (half by default, less against defended owners - the plot's steal_coins field is the exact payout) and the owner keeps and can still harvest the remainder; the plot records the share taken as raided_fraction. Limited to once per hour per neighbour and 3 raids per victim per day; a fully stripped build reports steal_reason stripped, and Security Fortress builds are immune.",
                auth="user",
                params=[
                    field("username", "path", "string", True, "alice", "Farm owner's username."),
                    field("slot", "form", "integer", True, "0", "Plot slot index, 0-based."),
                ],
                sample_response={"farm": {"owner_username": "alice"}, "stole_coins": 18},
            ),
            endpoint(
                id="game-fertilize",
                method="POST",
                path="/game/fertilize",
                title="Fertilize a build",
                summary="Spend coins to halve a growing build's remaining time (the plot's fertilize_cost field is the exact price). The price is computed from the exact value this build will pay out - including the golden multiplier and any active contract, Underdog, or Canary upside - so fertilizing is a pure time-skip and never a profit, on any build, at any prestige, with any combination of boosts.",
                auth="user",
                params=[field("slot", "form", "integer", True, "0", "Plot slot index, 0-based.")],
                sample_response={"ok": True, "farm": {"coins": 12}},
            ),
            endpoint(
                id="game-daily",
                method="POST",
                path="/game/daily",
                title="Claim daily bonus",
                summary="Claim the once-per-UTC-day coin bonus; consecutive days grow a streak (20 coins on day one up to 92 from day seven on), scaled by your own prestige and Tech Debt Payoff multiplier. A lapsed streak resets to day one - the farm state's daily_streak_reset flag and daily_reward already reflect that.",
                auth="user",
                sample_response={"ok": True, "farm": {"streak": 3, "coins": 94}},
            ),
            endpoint(
                id="game-perk",
                method="POST",
                path="/game/perk",
                title="Upgrade a perk",
                summary="Upgrade a permanent perk with coins: yield (+5% harvest coins), growth (+4% build speed), discount (-3% planting cost), or xp (+5% harvest XP) per level. Perks reset on refactor.",
                auth="user",
                params=[field("perk", "form", "string", True, "growth", "Perk key.", options=PERK_KEYS)],
                sample_response={"ok": True, "farm": {"coins": 0}},
            ),
            endpoint(
                id="game-quests-claim",
                method="POST",
                path="/game/quests/claim",
                title="Claim a quest",
                summary="Claim a completed daily quest by its kind, or (with scope=weekly, requires the Legacy Contracts Mastery upgrade) the weekly contract, which pays Stars plus a 48-hour +20% coin boost instead of coins.",
                auth="user",
                params=[
                    field("quest", "form", "string", True, "harvest", "Quest kind.", options=QUEST_KINDS),
                    field(
                        "scope",
                        "form",
                        "string",
                        False,
                        "daily",
                        "daily (default) or weekly.",
                        options=QUEST_SCOPES,
                    ),
                ],
                sample_response={"ok": True, "farm": {"coins": 130}},
            ),
            endpoint(
                id="game-prestige",
                method="POST",
                path="/game/prestige",
                title="Refactor (prestige)",
                summary="Reset the farm at level 10+ for a permanent +25% coin bonus and earn Stars to spend on Legacy upgrades. Refactoring costs a coin fee that scales with prestige and current wealth (the farm state's refactor_cost); the fee funds the community treasury and a fraction of the remaining coins (10% base, up to 35% with the Golden Parachute Legacy upgrade) carries over. From prestige 50 onward, every 10 more prestige also earns a permanent Mastery point.",
                auth="user",
                destructive=True,
                sample_response={"ok": True, "farm": {"prestige": 1, "coins": 6550}},
            ),
            endpoint(
                id="game-grant",
                method="POST",
                path="/game/grant",
                title="Claim the community grant",
                summary="Claim the weekly community grant, paid from the treasury filled by refactor fees and divided between everyone currently eligible (capped at 2500 coins, suppressed below 250). Eligible farms are active (5+ harvests this week), below 10000 coins, and at most prestige 5.",
                auth="user",
                sample_response={"ok": True, "farm": {"coins": 2550}},
            ),
            endpoint(
                id="game-legacy",
                method="POST",
                path="/game/legacy",
                title="Buy a Legacy upgrade",
                summary="Spend Stars on a permanent Legacy upgrade that survives every refactor: autoharvest (CI Bot), multiplier (+10% coins/level), speed (+5% build speed/level), plots (+1 starting plot/level), defense (+30s grace, -5% steal loss/level), or carryover (Golden Parachute, +5% refactor carry-over/level).",
                auth="user",
                params=[
                    field(
                        "key",
                        "form",
                        "string",
                        True,
                        "multiplier",
                        "Legacy upgrade key.",
                        options=LEGACY_KEYS,
                    )
                ],
                sample_response={"ok": True, "farm": {"stars": 1}},
            ),
            endpoint(
                id="game-mastery",
                method="POST",
                path="/game/mastery",
                title="Buy a Mastery upgrade",
                summary="Spend Mastery points (earned at prestige 50 and every 5 prestige after) on a permanent Mastery upgrade: autoreplant (Continuous Delivery, 3 points), analytics (Farm Analytics, 2 points), or contracts (Legacy Contracts, 4 points).",
                auth="user",
                params=[
                    field(
                        "key",
                        "form",
                        "string",
                        True,
                        "autoreplant",
                        "Mastery upgrade key.",
                        options=MASTERY_KEYS,
                    )
                ],
                sample_response={"ok": True, "farm": {"mastery_points": 0}},
            ),
            endpoint(
                id="game-infrastructure-buy",
                method="POST",
                path="/game/infrastructure/buy",
                title="Buy Infrastructure",
                summary="Buy a permanent, expensive, prestige-gated Infrastructure building: registry (Rust/Compiler/Kernel build 15% faster; 3M coins, prestige 3), canary (12% chance to double a harvest, 6% to only refund its planting cost; 6M, prestige 8), or observability (caps what any raider can take from you at 20% of a build's value; 15M, prestige 15).",
                auth="user",
                params=[
                    field(
                        "key",
                        "form",
                        "string",
                        True,
                        "registry",
                        "Infrastructure key.",
                        options=INFRA_KEYS,
                    )
                ],
                sample_response={"ok": True, "farm": {"coins": 0}},
            ),
            endpoint(
                id="game-defense-upgrade",
                method="POST",
                path="/game/defense/upgrade",
                title="Upgrade Defense",
                summary="Buy the next Defense tier (Firewall through Zero Trust Mesh; the farm state's defense_next_cost is the exact price). Each tier multiplicatively reduces what a raider takes from you and adds steal grace, but adds an ongoing daily coin upkeep of max(tier minimum, 0.2% of your balance). If you cannot pay, the tier decays by one level and only what you can afford is taken - your balance is never emptied.",
                auth="user",
                sample_response={"ok": True, "farm": {"defense_level": 1}},
            ),
            endpoint(
                id="game-defense-downgrade",
                method="POST",
                path="/game/defense/downgrade",
                title="Downgrade Defense",
                summary="Drop your Defense down one tier to escape its daily upkeep. There is no refund. Available whenever defense_downgrade_available is true in the farm state.",
                auth="user",
                sample_response={"ok": True, "farm": {"defense_level": 0}},
            ),
            endpoint(
                id="game-cosmetics-buy",
                method="POST",
                path="/game/cosmetics/buy",
                title="Buy a cosmetic",
                summary="Buy a purely cosmetic title or plot skin with coins. No gameplay effect. The farm state's cosmetics list carries each key, cost, and an owned flag.",
                auth="user",
                params=[
                    field(
                        "key",
                        "form",
                        "string",
                        True,
                        "title_architect",
                        "Cosmetic key.",
                        options=COSMETIC_KEYS,
                    )
                ],
                sample_response={"ok": True, "farm": {"coins": 0}},
            ),
            endpoint(
                id="game-cosmetics-equip",
                method="POST",
                path="/game/cosmetics/equip",
                title="Equip a title",
                summary="Equip an owned title cosmetic so its display name shows next to your name on the leaderboard.",
                auth="user",
                params=[
                    field(
                        "key",
                        "form",
                        "string",
                        True,
                        "title_architect",
                        "An owned title cosmetic key.",
                        options=COSMETIC_KEYS,
                    )
                ],
                sample_response={"ok": True, "farm": {"active_title": "title_architect"}},
            ),
        ],
}
