// PULSE API client — fetch wrapper with demo fallback for website visitors

const BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000'
const BASE = `${BASE_URL}/v1`

// Each endpoint tries the API independently (no global cache that kills all on one failure)
async function get<T>(path: string, demoData?: T): Promise<T> {
  try {
    const res = await fetch(`${BASE}${path}`, { signal: AbortSignal.timeout(5000) })
    if (!res.ok) throw new Error(`API ${res.status}: ${res.statusText}`)
    return res.json()
  } catch {
    if (demoData !== undefined) return demoData
    throw new Error('API unavailable')
  }
}

// --- Demo data (shown when API is not running) ---

const DEMO_OVERVIEW = {
  version: '10.51.2',
  agents: { total: 5, working: 3, idle: 2 },
  tasks: { open: 12, claimed: 3, done: 847 },
  orchestrator: { status: 'running', pid: 11960, uptime_hours: 72.4 },
  daemons: { alive: 10, dead: 0 },
}

const DEMO_AGENTS = {
  count: 5,
  agents: [
    { id: 'claude-opus-4-6', model: 'claude-opus-4-6', status: 'running', tier: 'premium', mode: 'interactive', tasks_completed: 184, trust_score: 0.95, current_task: 'Architecture audit', uptime: 14400, last_heartbeat: new Date().toISOString(), capabilities: ['edit', 'write', 'bash', 'agent'] },
    { id: 'claude-sonnet-4-6', model: 'claude-sonnet-4-6', status: 'running', tier: 'standard', mode: 'interactive', tasks_completed: 312, trust_score: 0.92, current_task: 'Feature implementation', uptime: 7200, last_heartbeat: new Date().toISOString(), capabilities: ['edit', 'write', 'bash'] },
    { id: 'gemini-2.5-pro', model: 'gemini-2.5-pro', status: 'running', tier: 'standard', mode: 'interactive', tasks_completed: 89, trust_score: 0.88, current_task: 'Code review', uptime: 3600, last_heartbeat: new Date().toISOString(), capabilities: ['edit', 'write'] },
    { id: 'claude-haiku-4-5', model: 'claude-haiku-4-5', status: 'idle', tier: 'fast', mode: 'swarm', tasks_completed: 1247, trust_score: 0.90, current_task: null, uptime: 0, last_heartbeat: null, capabilities: ['edit', 'write', 'bash'] },
    { id: 'qwen3-coder', model: 'ollama/qwen3-coder', status: 'idle', tier: 'fast', mode: 'swarm', tasks_completed: 456, trust_score: 0.85, current_task: null, uptime: 0, last_heartbeat: null, capabilities: ['edit', 'write'] },
  ],
}

const DEMO_WORKERS = {
  count: 3,
  workers: [
    { id: 'swarm-sonnet-01', model: 'claude-sonnet-4-6', tier: 'standard', status: 'running', tasks_completed: 23, current_task: 'Extract knowledge batch 4', last_heartbeat: new Date().toISOString() },
    { id: 'swarm-haiku-02', model: 'claude-haiku-4-5', tier: 'fast', status: 'running', tasks_completed: 67, current_task: 'Clean intents batch 7', last_heartbeat: new Date().toISOString() },
    { id: 'swarm-qwen-03', model: 'ollama/qwen3-coder', tier: 'fast', status: 'idle', tasks_completed: 12, current_task: null, last_heartbeat: null },
  ],
}

const DEMO_BRAIN_STATS = {
  total_synapses: 39136,
  integrity_ratio: 0.99,
  dimensions: {
    temporal_decay: { active: true },
    wilson_intervals: { active: true },
    contradiction: { active: true },
    agent_trust: { active: true },
    provenance: { active: true },
    working_memory: { active: true },
  },
  tables: {
    lessons: 10349, failures: 4862, patterns: 5788,
    facts: 6187, schemas: 446, procedures: 0,
    predictions: 0, anti_patterns: 57, decisions: 3,
    episodic: 195, evidence: 2949, intents: 9001,
  },
  wants: 5103, dont_wants: 6288, strategic_intents: 49,
  graph: { nodes: 26755, edges: 2895 },
  sessions: 22,
  search: { sources: 17, avg_latency_ms: 2467 },
}

const DEMO_TASKS = {
  status: 'ok',
  dispatches: [
    {
      id: 'd_001', created: '2026-03-29T08:00:00Z',
      tasks: [
        { id: 't_001', title: 'Implement FSRS-6 spaced retrieval', domain: 'brain', status: 'done', tier: 'premium' },
        { id: 't_002', title: 'Add temporal decay tests', domain: 'testing', status: 'done', tier: 'standard' },
        { id: 't_003', title: 'Update dashboard stats cards', domain: 'ui', status: 'claimed', tier: 'standard' },
      ],
    },
    {
      id: 'd_002', created: '2026-03-29T10:00:00Z',
      tasks: [
        { id: 't_004', title: 'Extract knowledge from session logs', domain: 'brain', status: 'open', tier: 'fast' },
        { id: 't_005', title: 'Clean duplicate intents', domain: 'brain', status: 'open', tier: 'fast' },
        { id: 't_006', title: 'Consolidation health check', domain: 'brain_ops', status: 'open', tier: 'fast' },
      ],
    },
  ],
}

const DEMO_LESSONS = {
  count: 8421, offset: 0, limit: 200,
  lessons: [
    'FSRS-6 uses retrievability R=(1+t/9S)^-1 for spacing effect; low R at recall gives bigger stability boost than high R',
    'Temporal decay in PULSE uses power-law (1+t/HL)^-0.5 giving heavier weight to recent memories than exponential decay',
    'Context compaction is lossy by design \u2014 anything that needs to survive compaction should live in external state',
    'Enforcement at write-time beats enforcement at prompt-time. Hooks are deterministic; prompts are probabilistic',
    'Positive rules outperform negative rules. "Always use TypeScript strict mode" beats "never use any"',
    'Continuous extraction during the session beats batch save at the end \u2014 captures the "why" behind decisions',
    'At 12+ concurrent agents, filelock timeout must be 60s+ to prevent write-lock convoy crashes',
    'Agent trust (Dimension B) should only apply to items from known agents, not default 0.3 for brain sources',
    'SQLite WAL mode with busy_timeout 60s handles concurrent daemon writes without corruption',
    'Pre-commit SoC enforcement (300 lines, 5 functions) catches architectural drift before it compounds',
  ],
}

const DEMO_FAILURES = {
  count: 2134, offset: 0, limit: 200,
  failures: [
    'SM-2 algorithm had no spacing effect \u2014 items recalled fresh got same boost as almost-forgotten items. Fixed by FSRS-6 upgrade',
    'Agent trust multiplied ALL results by 0.3 default, killing search quality. Fixed to only apply trust to known agent items',
    'sys.exit() in library code killed the orchestrator instead of raising an error. Use RuntimeError instead',
    'Module-level stdout wrapping crashed terminal on Windows cp1252 encoding. Use __name__ == "__main__" guard',
    'Capture log naming without agent suffix caused 8-day gap and 1.3MB data loss. Bridge reads suffixed names only',
    'Compliance validator deleted unsigned JSON in state/ root \u2014 system files need _SYSTEM_FILES skip list',
  ],
}

const DEMO_PATTERNS = {
  count: 1847, offset: 0, limit: 200,
  patterns: [
    'Hook-based enforcement > prompt-based enforcement for production governance',
    'Knowledge items need temporal decay \u2014 unreinforced items should lose confidence over time',
    'Cross-agent learning requires shared persistent memory, not per-agent context',
    'Contradiction detection at storage layer prevents wasted reasoning tokens downstream',
    'Evidence-weighted promotion: patterns need 3+ independent confirmations before becoming active blockers',
  ],
}

const DEMO_GRAPH = {
  nodes: 8462,
  edges: 23891,
  data: {
    nodes: Array.from({ length: 50 }, (_, i) => ({
      id: `n${i}`,
      label: ['FSRS-6', 'temporal decay', 'consolidation', 'knowledge graph', 'brain search',
              'Wilson intervals', 'anti-patterns', 'SoC enforcement', 'constitutional governance',
              'multi-agent trust', 'session lifecycle', 'spaced retrieval', 'prediction daemon',
              'compliance validator', 'capture bridge', 'knowledge extraction', 'pattern promotion',
              'provenance chain', 'PII filter', 'orchestrator', 'worker dispatch', 'task board',
              'brain boot', 'drift detection', 'circuit breaker', 'semantic extraction',
              'hot cache', 'inverted index', 'quality gate', 'salience scoring',
              'confidence decay', 'overlearning resistance', 'arousal modulation',
              'episodic memory', 'working memory', 'schema promotion', 'reconsolidation',
              'deduplication', 'brain health', 'sleep cycle', 'DMN ideation',
              'hebbian balancing', 'ghost resonance', 'skill injection', 'neural render',
              'reward signal', 'prediction feedback', 'founder auth', 'evidence accumulator',
              'curriculum learning'][i],
      type: ['algorithm', 'daemon', 'module', 'concept', 'security'][i % 5],
    })),
    edges: Array.from({ length: 120 }, (_, i) => ({
      from: `n${i % 50}`,
      to: `n${(i * 7 + 13) % 50}`,
      relation: ['uses', 'triggers', 'feeds', 'validates', 'depends_on'][i % 5],
    })),
  },
}

const DEMO_SCHEMAS = { count: 340, schemas: [{ name: 'lesson_schema', fields: 12 }, { name: 'failure_schema', fields: 8 }] }
const DEMO_PROCEDURES = { count: 189, procedures: [{ name: 'consolidation_pipeline', steps: 7 }, { name: 'boot_sequence', steps: 5 }] }
const DEMO_WANTS = { count: 42, wants: [{ want: 'Improve search relevance scoring', priority: 2 }] }
const DEMO_DONT_WANTS = { count: 18, dont_wants: [{ dont_want: 'Never pass prediction_error to reconsolidation', reason: 'write-only by design' }] }
const DEMO_INTENTS = { count: 5, strategic_intents: [{ intent: 'Repository Census (50 Sonnets)', status: 'pending' }] }
const DEMO_ANTI_PATTERNS = { count: 94, anti_patterns: [{ pattern: 'sys.exit() in library code', severity: 'critical', confirmed: true }] }

// Brain endpoints with demo fallback
export const api = {
  getSystemOverview: () => get<any>('/system/overview', DEMO_OVERVIEW),
  getAgents: () => get('/agents', DEMO_AGENTS),
  getWorkers: () => get('/workers', DEMO_WORKERS),
  getBrainStats: () => get<any>('/brain/stats', DEMO_BRAIN_STATS),
  getBrainHealth: () => get<any>('/brain/health', { status: 'healthy', checks: [] }),
  getTasks: () => get('/brain/tasks', DEMO_TASKS),
  getLessons: (offset = 0, limit = 200) => get(`/brain/lessons?offset=${offset}&limit=${limit}`, DEMO_LESSONS),
  getFailures: (offset = 0, limit = 200) => get(`/brain/failures?offset=${offset}&limit=${limit}`, DEMO_FAILURES),
  getPatterns: (offset = 0, limit = 200) => get(`/brain/patterns?offset=${offset}&limit=${limit}`, DEMO_PATTERNS),
  getGraph: () => get('/brain/graph', DEMO_GRAPH),
  getSchemas: () => get('/brain/schemas', DEMO_SCHEMAS),
  getProcedures: () => get('/brain/procedures', DEMO_PROCEDURES),
  getWants: () => get('/brain/wants', DEMO_WANTS),
  getDontWants: () => get('/brain/dont_wants', DEMO_DONT_WANTS),
  getStrategicIntents: () => get('/brain/strategic_intents', DEMO_INTENTS),
  getAntiPatterns: () => get('/brain/anti_patterns', DEMO_ANTI_PATTERNS),
  searchBrain: (q: string) => get<any>(`/brain/search?q=${encodeURIComponent(q)}`, { query: q, total_results: 0, results: [] }),
}
