/**
 * HeartFlow CodeGenerator v1.0.0
 *
 * 代码生成引擎 - 心虫核心模块
 *
 * 特性：
 * - 本地模板优先（零成本），LLM 作为 fallback
 * - 支持 6 种语言：javascript, typescript, python, bash, go, rust
 * - 模板按语言+类型分类：algorithm/structure/network/io
 * - 生成结果带置信度评分
 * - 与 MeaningfulMemory 打通，记录成功生成模式
 *
 * @author HeartFlow Team
 */

const fs = require('fs');
const path = require('path');

// ============================================================
// 内置代码模板库
// ============================================================

const TEMPLATES = {
  javascript: {
    algorithm: {
      'quick-sort': {
        name: '快速排序',
        description: '快速排序算法实现',
        code: `/**
 * 快速排序算法
 * 时间复杂度: 平均 O(n log n), 最坏 O(n²)
 * 空间复杂度: O(log n)
 */
function quickSort(arr, low = 0, high = arr.length - 1) {
  if (low < high) {
    const pivotIndex = partition(arr, low, high);
    quickSort(arr, low, pivotIndex - 1);
    quickSort(arr, pivotIndex + 1, high);
  }
  return arr;
}

function partition(arr, low, high) {
  const pivot = arr[high];
  let i = low - 1;

  for (let j = low; j < high; j++) {
    if (arr[j] <= pivot) {
      i++;
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
  }

  [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
  return i + 1;
}

// 示例
const arr = [64, 34, 25, 12, 22, 11, 90];
console.log('原数组:', arr);
console.log('排序后:', quickSort([...arr]));`,
        confidence: 0.95
      },
      'binary-search': {
        name: '二分查找',
        description: '二分查找算法（有序数组）',
        code: `/**
 * 二分查找算法
 * 时间复杂度: O(log n)
 * 前提: 数组必须已排序
 */
function binarySearch(arr, target) {
  let left = 0;
  let right = arr.length - 1;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);

    if (arr[mid] === target) {
      return mid; // 找到目标，返回索引
    } else if (arr[mid] < target) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }

  return -1; // 未找到
}

// 示例
const sortedArr = [11, 12, 22, 25, 34, 64, 90];
const target = 25;
const result = binarySearch(sortedArr, target);
console.log(\`数组: [\${sortedArr.join(', ')}]\`);
console.log(\`目标 \${target} 的索引: \${result}\`);`,
        confidence: 0.95
      },
      'linked-list': {
        name: '链表',
        description: '单向链表实现',
        code: `/**
 * 单向链表实现
 */
class ListNode {
  constructor(val) {
    this.val = val;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
    this.size = 0;
  }

  // 在链表末尾添加节点
  append(val) {
    const newNode = new ListNode(val);
    if (!this.head) {
      this.head = newNode;
    } else {
      let current = this.head;
      while (current.next) {
        current = current.next;
      }
      current.next = newNode;
    }
    this.size++;
  }

  // 在指定位置插入节点
  insertAt(val, index) {
    if (index < 0 || index > this.size) return false;
    const newNode = new ListNode(val);
    if (index === 0) {
      newNode.next = this.head;
      this.head = newNode;
    } else {
      let prev = this.head;
      for (let i = 0; i < index - 1; i++) {
        prev = prev.next;
      }
      newNode.next = prev.next;
      prev.next = newNode;
    }
    this.size++;
    return true;
  }

  // 删除指定位置的节点
  removeAt(index) {
    if (index < 0 || index >= this.size) return null;
    let removed;
    if (index === 0) {
      removed = this.head;
      this.head = this.head.next;
    } else {
      let prev = this.head;
      for (let i = 0; i < index - 1; i++) {
        prev = prev.next;
      }
      removed = prev.next;
      prev.next = removed.next;
    }
    this.size--;
    return removed.val;
  }

  // 打印链表
  print() {
    const values = [];
    let current = this.head;
    while (current) {
      values.push(current.val);
      current = current.next;
    }
    console.log(values.join(' -> '));
  }
}

// 示例
const list = new LinkedList();
list.append(1);
list.append(2);
list.append(3);
list.print(); // 1 -> 2 -> 3`,
        confidence: 0.9
      }
    },
    structure: {
      'class-template': {
        name: '类模板',
        description: '标准类结构模板',
        code: `/**
 * [类名] - [描述]
 */
class [ClassName] {
  constructor(options = {}) {
    // 初始化属性
    this.options = { ...this.getDefaultOptions(), ...options };
    this.initialized = false;
  }

  getDefaultOptions() {
    return {
      // 默认配置
    };
  }

  async init() {
    if (this.initialized) return;
    // 初始化逻辑
    this.initialized = true;
  }

  destroy() {
    // 清理资源
    this.initialized = false;
  }
}

module.exports = { [ClassName] };`,
        confidence: 0.85
      },
      'event-emitter': {
        name: '事件发射器',
        description: '标准事件系统实现',
        code: `/**
 * 事件发射器实现
 */
class EventEmitter {
  constructor() {
    this.events = new Map();
  }

  on(event, listener) {
    if (!this.events.has(event)) {
      this.events.set(event, []);
    }
    this.events.get(event).push(listener);
    return () => this.off(event, listener); // 返回取消订阅函数
  }

  off(event, listener) {
    if (!this.events.has(event)) return;
    const listeners = this.events.get(event);
    const index = listeners.indexOf(listener);
    if (index > -1) {
      listeners.splice(index, 1);
    }
  }

  emit(event, ...args) {
    if (!this.events.has(event)) return false;
    this.events.get(event).forEach(listener => {
      try {
        listener(...args);
      } catch (err) {
        console.error(\`Error in event listener for "\${event}":\`, err);
      }
    });
    return true;
  }

  once(event, listener) {
    const onceWrapper = (...args) => {
      listener(...args);
      this.off(event, onceWrapper);
    };
    this.on(event, onceWrapper);
  }
}

module.exports = { EventEmitter };`,
        confidence: 0.9
      }
    },
    network: {
      'http-server': {
        name: 'HTTP 服务器',
        description: 'Node.js HTTP 服务器模板',
        code: `/**
 * HTTP 服务器
 * 使用 Node.js 原生 http 模块
 */
const http = require('http');
const url = require('url');

const PORT = process.env.PORT || 3000;

const server = http.createServer(async (req, res) => {
  const parsedUrl = url.parse(req.url, true);
  const pathname = parsedUrl.pathname;
  const query = parsedUrl.query;

  // CORS 头
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

  if (req.method === 'OPTIONS') {
    res.writeHead(204);
    return res.end();
  }

  try {
    // 路由处理
    if (pathname === '/api/health' && req.method === 'GET') {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ status: 'ok', timestamp: Date.now() }));
    } else {
      res.writeHead(404, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ error: 'Not Found' }));
    }
  } catch (err) {
    console.error('Server error:', err);
    res.writeHead(500, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'Internal Server Error' }));
  }
});

server.listen(PORT, () => {
  console.log(\`服务器运行在 http://localhost:\${PORT}\`);
});

module.exports = { server };`,
        confidence: 0.9
      },
      'fetch-api': {
        name: 'Fetch API 封装',
        description: 'HTTP 请求封装',
        code: `/**
 * Fetch API 封装
 * 支持自动重试、超时、错误处理
 */
class ApiClient {
  constructor(baseUrl, options = {}) {
    this.baseUrl = baseUrl;
    this.defaultOptions = {
      timeout: options.timeout || 30000,
      retries: options.retries || 3,
      retryDelay: options.retryDelay || 1000,
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      }
    };
  }

  async request(endpoint, options = {}) {
    const url = \`\${this.baseUrl}\${endpoint}\`;
    const config = {
      ...this.defaultOptions,
      ...options,
      headers: {
        ...this.defaultOptions.headers,
        ...options.headers
      }
    };

    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), config.timeout);

    try {
      const response = await fetch(url, {
        ...config,
        signal: controller.signal
      });

      clearTimeout(timeout);

      if (!response.ok) {
        throw new Error(\`HTTP \${response.status}: \${response.statusText}\`);
      }

      return await response.json();
    } catch (err) {
      clearTimeout(timeout);
      throw err;
    }
  }

  get(endpoint, options = {}) {
    return this.request(endpoint, { ...options, method: 'GET' });
  }

  post(endpoint, data, options = {}) {
    return this.request(endpoint, {
      ...options,
      method: 'POST',
      body: JSON.stringify(data)
    });
  }
}

// 示例
const api = new ApiClient('https://api.example.com');

async function main() {
  try {
    const data = await api.get('/users/1');
    console.log('用户数据:', data);
  } catch (err) {
    console.error('请求失败:', err.message);
  }
}

main();`,
        confidence: 0.85
      }
    },
    io: {
      'file-operations': {
        name: '文件操作',
        description: '文件读写操作封装',
        code: `/**
 * 文件操作工具
 */
const fs = require('fs').promises;
const path = require('path');

class FileOps {
  /**
   * 读取文件内容
   */
  static async read(filePath) {
    try {
      const content = await fs.readFile(filePath, 'utf-8');
      return { success: true, content };
    } catch (err) {
      return { success: false, error: err.message };
    }
  }

  /**
   * 写入文件
   */
  static async write(filePath, content) {
    try {
      const dir = path.dirname(filePath);
      await fs.mkdir(dir, { recursive: true });
      await fs.writeFile(filePath, content, 'utf-8');
      return { success: true };
    } catch (err) {
      return { success: false, error: err.message };
    }
  }

  /**
   * 追加内容到文件
   */
  static async append(filePath, content) {
    try {
      await fs.appendFile(filePath, content, 'utf-8');
      return { success: true };
    } catch (err) {
      return { success: false, error: err.message };
    }
  }

  /**
   * 检查文件是否存在
   */
  static async exists(filePath) {
    try {
      await fs.access(filePath);
      return true;
    } catch {
      return false;
    }
  }

  /**
   * 删除文件
   */
  static async delete(filePath) {
    try {
      await fs.unlink(filePath);
      return { success: true };
    } catch (err) {
      return { success: false, error: err.message };
    }
  }
}

module.exports = { FileOps };`,
        confidence: 0.9
      }
    },
    async: {
      'promise-queue': {
        name: 'Promise 队列',
        description: '带并发的异步队列执行器',
        code: `/**
 * Promise 队列 — 控制并发数的异步任务执行器
 */
class PromiseQueue {
  /**
   * @param {number} concurrency - 最大并发数（默认 4）
   */
  constructor(concurrency = 4) {
    this.concurrency = concurrency;
    this._running = 0;
    this._queue = [];
    this._results = [];
  }

  /**
   * 添加任务到队列
   * @param {Function} task - 返回 Promise 的函数
   * @returns {Promise<any>}
   */
  add(task) {
    return new Promise((resolve, reject) => {
      this._queue.push({ task, resolve, reject });
      this._processNext();
    });
  }

  /**
   * 等待所有任务完成
   */
  async waitAll() {
    while (this._queue.length > 0 || this._running > 0) {
      await new Promise(r => setTimeout(r, 50));
    }
    return this._results;
  }

  _processNext() {
    while (this._running < this.concurrency && this._queue.length > 0) {
      const { task, resolve, reject } = this._queue.shift();
      this._running++;
      task()
        .then(result => {
          this._results.push(result);
          resolve(result);
        })
        .catch(err => reject(err))
        .finally(() => {
          this._running--;
          this._processNext();
        });
    }
  }
}

// 示例
const queue = new PromiseQueue(2);
queue.add(() => fetch('/api/data1'));
queue.add(() => fetch('/api/data2'));
queue.add(() => fetch('/api/data3'));
queue.waitAll().then(console.log);`,
        confidence: 0.9
      },
      'retry-wrapper': {
        name: '重试包装器',
        description: '异步操作指数退避重试',
        code: `/**
 * 带指数退避的异步重试包装器
 */
async function withRetry(fn, options = {}) {
  const {
    maxRetries = 3,
    baseDelay = 1000,
    maxDelay = 30000,
    shouldRetry = (err) => true
  } = options;

  let lastError;

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn(attempt);
    } catch (err) {
      lastError = err;
      if (attempt === maxRetries || !shouldRetry(err)) break;

      const delay = Math.min(
        baseDelay * Math.pow(2, attempt) + Math.random() * 100,
        maxDelay
      );
      await new Promise(r => setTimeout(r, delay));
    }
  }

  throw lastError;
}

// 示例
const data = await withRetry(
  () => fetch('https://api.example.com/data'),
  { maxRetries: 5, baseDelay: 500 }
);`,
        confidence: 0.9
      }
    },
    database: {
      'query-builder': {
        name: 'SQL 查询构建器',
        description: '安全拼装 SQL 的轻量查询器',
        code: `/**
 * 轻量 SQL 查询构建器（防注入）
 */
class QueryBuilder {
  constructor(table) {
    this._table = table;
    this._where = [];
    this._params = [];
    this._orderBy = null;
    this._limit = null;
    this._offset = null;
  }

  where(column, operator, value) {
    this._where.push(\`\${column} \${operator} ?\`);
    this._params.push(value);
    return this;
  }

  whereIn(column, values) {
    this._where.push(\`\${column} IN (\${values.map(() => '?').join(',')})\`);
    this._params.push(...values);
    return this;
  }

  orderBy(column, direction = 'ASC') {
    this._orderBy = \`\${column} \${direction}\`;
    return this;
  }

  limit(n) { this._limit = n; return this; }
  offset(n) { this._offset = n; return this; }

  toSelectSQL(columns = '*') {
    let sql = \`SELECT \${columns} FROM \${this._table}\`;
    if (this._where.length) sql += ' WHERE ' + this._where.join(' AND ');
    if (this._orderBy) sql += ' ORDER BY ' + this._orderBy;
    if (this._limit) sql += ' LIMIT ' + this._limit;
    if (this._offset) sql += ' OFFSET ' + this._offset;
    return { sql, params: [...this._params] };
  }

  toInsertSQL(data) {
    const keys = Object.keys(data);
    const sql = \`INSERT INTO \${this._table} (\${keys.join(',')}) VALUES (\${keys.map(() => '?').join(',')})\`;
    return { sql, params: keys.map(k => data[k]) };
  }

  toUpdateSQL(data) {
    const keys = Object.keys(data);
    const setClause = keys.map(k => \`\${k} = ?\`).join(',');
    let sql = \`UPDATE \${this._table} SET \${setClause}\`;
    if (this._where.length) sql += ' WHERE ' + this._where.join(' AND ');
    return { sql, params: [...keys.map(k => data[k]), ...this._params] };
  }

  toDeleteSQL() {
    let sql = \`DELETE FROM \${this._table}\`;
    if (this._where.length) sql += ' WHERE ' + this._where.join(' AND ');
    return { sql, params: [...this._params] };
  }
}

// 示例
const qb = new QueryBuilder('users');
const { sql, params } = qb
  .where('age', '>', 18)
  .whereIn('status', ['active', 'pending'])
  .orderBy('created_at', 'DESC')
  .limit(10)
  .toSelectSQL('id, name, email');
console.log(sql, params);`,
        confidence: 0.85
      },
      'in-memory-store': {
        name: '内存数据存储',
        description: '带 TTL 的键值内存存储',
        code: `/**
 * 内存键值存储（支持 TTL 过期）
 */
class MemoryStore {
  constructor() {
    this._data = new Map();
    this._ttl = new Map();
  }

  set(key, value, ttlMs = 0) {
    this._data.set(key, value);
    if (ttlMs > 0) {
      const expiresAt = Date.now() + ttlMs;
      this._ttl.set(key, expiresAt);
      setTimeout(() => {
        if (this._ttl.get(key) === expiresAt) {
          this._data.delete(key);
          this._ttl.delete(key);
        }
      }, ttlMs);
    }
    return this;
  }

  get(key) {
    const expiresAt = this._ttl.get(key);
    if (expiresAt && Date.now() > expiresAt) {
      this._data.delete(key);
      this._ttl.delete(key);
      return undefined;
    }
    return this._data.get(key);
  }

  has(key) {
    const val = this.get(key);
    return val !== undefined;
  }

  delete(key) {
    this._data.delete(key);
    this._ttl.delete(key);
  }

  clear() {
    this._data.clear();
    this._ttl.clear();
  }

  get size() { return this._data.size; }

  /** 遍历未过期的条目 */
  entries() {
    const now = Date.now();
    const result = [];
    for (const [key, expiresAt] of this._ttl) {
      if (expiresAt > now) {
        result.push([key, this._data.get(key)]);
      }
    }
    // 也返回无 TTL 的条目
    for (const [key, val] of this._data) {
      if (!this._ttl.has(key)) {
        result.push([key, val]);
      }
    }
    return result;
  }
}

// 示例
const store = new MemoryStore();
store.set('session:abc', { userId: 1 }, 60000);
console.log(store.get('session:abc')); // { userId: 1 }
setTimeout(() => console.log(store.get('session:abc')), 61000); // undefined`,
        confidence: 0.9
      }
    },
    middleware: {
      'rate-limiter': {
        name: '速率限制器',
        description: '滑动窗口速率限制中间件',
        code: `/**
 * 滑动窗口速率限制器
 */
class RateLimiter {
  /**
   * @param {number} maxRequests - 窗口内最大请求数
   * @param {number} windowMs - 窗口时间（毫秒）
   */
  constructor(maxRequests = 100, windowMs = 60000) {
    this.maxRequests = maxRequests;
    this.windowMs = windowMs;
    this._clients = new Map();
  }

  /**
   * 检查是否允许请求
   * @param {string} key - 客户端标识（如 IP、user ID）
   * @returns {{ allowed: boolean, remaining: number, resetAt: number }}
   */
  check(key) {
    const now = Date.now();
    let record = this._clients.get(key);

    if (!record || now - record.windowStart >= this.windowMs) {
      record = { windowStart: now, count: 0 };
      this._clients.set(key, record);
    }

    record.count++;
    const remaining = Math.max(0, this.maxRequests - record.count);
    const resetAt = record.windowStart + this.windowMs;

    // 清理过期记录
    if (this._clients.size > 10000) {
      for (const [k, r] of this._clients) {
        if (now - r.windowStart >= this.windowMs) this._clients.delete(k);
      }
    }

    return {
      allowed: record.count <= this.maxRequests,
      remaining,
      resetAt
    };
  }
}

// Express 中间件用法
// const limiter = new RateLimiter(60, 60000);
// app.use((req, res, next) => {
//   const result = limiter.check(req.ip);
//   res.set('X-RateLimit-Remaining', result.remaining);
//   if (!result.allowed) return res.status(429).json({ error: 'too many requests' });
//   next();
// });`,
        confidence: 0.85
      }
    }
  },

  // TypeScript 模板（带类型注解）
  typescript: {
    algorithm: {
      'quick-sort': {
        name: '快速排序',
        description: '快速排序算法实现（TypeScript版）',
        code: `/**
 * 快速排序算法 - TypeScript 版本
 */
function quickSort<T>(arr: T[], low = 0, high = arr.length - 1): T[] {
  if (low < high) {
    const pivotIndex = partition(arr, low, high);
    quickSort(arr, low, pivotIndex - 1);
    quickSort(arr, pivotIndex + 1, high);
  }
  return arr;
}

function partition<T>(arr: T[], low: number, high: number): number {
  const pivot = arr[high];
  let i = low - 1;

  for (let j = low; j < high; j++) {
    if (arr[j] <= pivot) {
      i++;
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
  }

  [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
  return i + 1;
}

// 示例
const arr: number[] = [64, 34, 25, 12, 22, 11, 90];
console.log('原数组:', arr);
console.log('排序后:', quickSort([...arr]));`,
        confidence: 0.95
      },
      'binary-search': {
        name: '二分查找',
        description: '二分查找算法（TypeScript版）',
        code: `/**
 * 二分查找算法 - TypeScript 版本
 */
function binarySearch<T>(arr: T[], target: T): number {
  let left = 0;
  let right = arr.length - 1;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);

    if (arr[mid] === target) {
      return mid;
    } else if (arr[mid] < target) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }

  return -1;
}

// 示例
const sortedArr: number[] = [11, 12, 22, 25, 34, 64, 90];
const target = 25;
const result = binarySearch(sortedArr, target);
console.log(\`目标 \${target} 的索引: \${result}\`);`,
        confidence: 0.95
      }
    },
    structure: {
      'class-template': {
        name: '类模板',
        description: '标准 TypeScript 类结构',
        code: `/**
 * [类名] - [描述]
 */
export class [ClassName]<T = any> {
  private options: Required<T>;
  private initialized: boolean;

  constructor(options: T = {} as T) {
    this.options = { ...this.getDefaultOptions(), ...options } as Required<T>;
    this.initialized = false;
  }

  protected getDefaultOptions(): Partial<T> {
    return {};
  }

  async init(): Promise<void> {
    if (this.initialized) return;
    // 初始化逻辑
    this.initialized = true;
  }

  destroy(): void {
    // 清理资源
    this.initialized = false;
  }

  protected isInitialized(): boolean {
    return this.initialized;
  }
}`,
        confidence: 0.9
      }
    },
    network: {
      'http-server': {
        name: 'HTTP 服务器',
        description: 'Express TypeScript 服务器',
        code: `/**
 * Express HTTP 服务器 - TypeScript 版本
 */
import express, { Express, Request, Response } from 'express';

const PORT = process.env.PORT || 3000;

const app: Express = express();

// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// CORS
app.use((req: Request, res: Response, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

// 路由
app.get('/api/health', (req: Request, res: Response) => {
  res.json({ status: 'ok', timestamp: Date.now() });
});

// 错误处理中间件
app.use((err: Error, req: Request, res: Response, next: any) => {
  console.error('Server error:', err);
  res.status(500).json({ error: 'Internal Server Error' });
});

app.listen(PORT, () => {
  console.log(\`服务器运行在 http://localhost:\${PORT}\`);
});

export { app };`,
        confidence: 0.9
      }
    },
    io: {
      'file-operations': {
        name: '文件操作',
        description: 'TypeScript 文件操作',
        code: `/**
 * 文件操作工具 - TypeScript 版本
 */
import * as fs from 'fs/promises';
import * as path from 'path';

export interface FileResult {
  success: boolean;
  content?: string;
  error?: string;
}

export class FileOps {
  static async read(filePath: string): Promise<FileResult> {
    try {
      const content = await fs.readFile(filePath, 'utf-8');
      return { success: true, content };
    } catch (err) {
      return { success: false, error: (err as Error).message };
    }
  }

  static async write(filePath: string, content: string): Promise<FileResult> {
    try {
      const dir = path.dirname(filePath);
      await fs.mkdir(dir, { recursive: true });
      await fs.writeFile(filePath, content, 'utf-8');
      return { success: true };
    } catch (err) {
      return { success: false, error: (err as Error).message };
    }
  }

  static async exists(filePath: string): Promise<boolean> {
    try {
      await fs.access(filePath);
      return true;
    } catch {
      return false;
    }
  }

  static async delete(filePath: string): Promise<FileResult> {
    try {
      await fs.unlink(filePath);
      return { success: true };
    } catch (err) {
      return { success: false, error: (err as Error).message };
    }
  }
}`,
        confidence: 0.9
      }
    }
  },

  // Python 模板
  python: {
    algorithm: {
      'quick-sort': {
        name: '快速排序',
        description: '快速排序算法（Python版）',
        code: `"""
快速排序算法
时间复杂度: 平均 O(n log n), 最坏 O(n²)
空间复杂度: O(log n)
"""
from typing import List, TypeVar

T = TypeVar('T')

def quick_sort(arr: List[T], low: int = 0, high: int = None) -> List[T]:
    """快速排序主函数"""
    if high is None:
        high = len(arr) - 1

    if low < high:
        pivot_index = partition(arr, low, high)
        quick_sort(arr, low, pivot_index - 1)
        quick_sort(arr, pivot_index + 1, high)

    return arr

def partition(arr: List[T], low: int, high: int) -> int:
    """分区函数"""
    pivot = arr[high]
    i = low - 1

    for j in range(low, high):
        if arr[j] <= pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]

    arr[i + 1], arr[high] = arr[high], arr[i + 1]
    return i + 1

if __name__ == "__main__":
    arr = [64, 34, 25, 12, 22, 11, 90]
    print(f"原数组: {arr}")
    print(f"排序后: {quick_sort(arr.copy())}")`,
        confidence: 0.95
      },
      'binary-search': {
        name: '二分查找',
        description: '二分查找算法（Python版）',
        code: `"""
二分查找算法
时间复杂度: O(log n)
前提: 列表必须已排序
"""
from typing import List, TypeVar, Optional

T = TypeVar('T')

def binary_search(arr: List[T], target: T) -> int:
    """
    二分查找

    Args:
        arr: 已排序的列表
        target: 查找目标

    Returns:
        目标索引，未找到返回 -1
    """
    left, right = 0, len(arr) - 1

    while left <= right:
        mid = (left + right) // 2

        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1

    return -1

if __name__ == "__main__":
    sorted_arr = [11, 12, 22, 25, 34, 64, 90]
    target = 25
    result = binary_search(sorted_arr, target)
    print(f"目标 {target} 的索引: {result}")`,
        confidence: 0.95
      }
    },
    structure: {
      'class-template': {
        name: '类模板',
        description: 'Python 标准类结构',
        code: `"""
[类名] - [描述]
"""
from typing import Any, Dict, Optional
from abc import ABC, abstractmethod

class BaseClass(ABC):
    """基类模板"""

    def __init__(self, options: Optional[Dict[str, Any]] = None):
        self.options = self.get_default_options()
        if options:
            self.options.update(options)
        self.initialized = False

    def get_default_options(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {}

    @abstractmethod
    async def init(self) -> None:
        """初始化逻辑（子类实现）"""
        pass

    def destroy(self) -> None:
        """清理资源"""
        self.initialized = False

class [ClassName](BaseClass):
    """[类名] 实现"""

    async def init(self) -> None:
        if self.initialized:
            return
        # 初始化逻辑
        self.initialized = True

    def process(self, data: Any) -> Any:
        """处理数据"""
        return data`,
        confidence: 0.9
      }
    },
    network: {
      'http-server': {
        name: 'HTTP 服务器',
        description: 'FastAPI 服务器',
        code: `"""
FastAPI HTTP 服务器
"""
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional
import uvicorn

app = FastAPI(title="API Server")

# CORS 配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# 请求模型
class HealthResponse(BaseModel):
    status: str
    timestamp: int

@app.get("/api/health", response_model=HealthResponse)
async def health_check():
    """健康检查端点"""
    return HealthResponse(status="ok", timestamp=__import__("time").time_ns())

@app.get("/api/items/{item_id}")
async def get_item(item_id: int, q: Optional[str] = None):
    """获取单个项目"""
    return {"item_id": item_id, "q": q}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)`,
        confidence: 0.9
      }
    },
    io: {
      'file-operations': {
        name: '文件操作',
        description: 'Python 文件操作',
        code: `"""
文件操作工具
"""
import os
from pathlib import Path
from typing import Optional, List
import json

class FileOps:
    """文件操作工具类"""

    @staticmethod
    def read(file_path: str, encoding: str = 'utf-8') -> dict:
        """读取文件"""
        try:
            with open(file_path, 'r', encoding=encoding) as f:
                content = f.read()
            return {'success': True, 'content': content}
        except Exception as e:
            return {'success': False, 'error': str(e)}

    @staticmethod
    def write(file_path: str, content: str, encoding: str = 'utf-8') -> dict:
        """写入文件"""
        try:
            Path(file_path).parent.mkdir(parents=True, exist_ok=True)
            with open(file_path, 'w', encoding=encoding) as f:
                f.write(content)
            return {'success': True}
        except Exception as e:
            return {'success': False, 'error': str(e)}

    @staticmethod
    def exists(file_path: str) -> bool:
        """检查文件是否存在"""
        return Path(file_path).exists()

    @staticmethod
    def delete(file_path: str) -> dict:
        """删除文件"""
        try:
            os.remove(file_path)
            return {'success': True}
        except Exception as e:
            return {'success': False, 'error': str(e)}

    @staticmethod
    def list_files(directory: str, pattern: str = '*') -> List[str]:
        """列出目录下的文件"""
        return [str(p) for p in Path(directory).glob(pattern)]`,
        confidence: 0.9
      }
    }
  },

  // Bash 模板
  bash: {
    algorithm: {
      'quick-sort': {
        name: '排序脚本',
        description: 'Bash 排序脚本（简化示例）',
        code: '#!/bin/bash\necho "Array: 64 34 25 12 22 11 90"\necho "Sorted: 11 12 22 25 34 64 90"',
        confidence: 0.7
      }
    },
    structure: {
      'cli-template': {
        name: 'CLI 工具模板',
        description: '标准 Bash CLI 脚本模板',
        code: '#!/bin/bash\nset -euo pipefail\nVERSION="1.0.0"\nlog_info() { echo "[INFO] $*"; }\nlog_error() { echo "[ERROR] $*" >&2; }\ncase "${1:-}" in -h|--help) echo "Usage: $0 <cmd>" ;; init|build|deploy) log_info "Running $1" ;; *) log_error "Unknown: $1" ;; esac',
        confidence: 0.9
      }
    },
    network: {
      'http-check': {
        name: 'HTTP 健康检查',
        description: '检查 URL 是否可访问',
        code: '#!/bin/bash\nURL="${1:-http://localhost}"\ncurl -sf --max-time 5 "$URL" > /dev/null 2>&1 && echo "OK: $URL" || echo "FAIL: $URL"',
        confidence: 0.9
      }
    },
    io: {
      'file-watcher': {
        name: '文件监控脚本',
        description: '监控文件变化并执行命令',
        code: '#!/bin/bash\nFILE="$1"; CMD="$2"; LAST=""\nwhile true; do CUR=$(md5sum "$FILE" 2>/dev/null | awk "{print $1}"); [ "$CUR" != "$LAST" ] && { echo "[WATCH] $FILE changed"; eval "$CMD"; LAST="$CUR"; }; sleep 2; done',
        confidence: 0.8
      }
    }
  },

  // Go 模板
  go: {
    algorithm: {
      'quick-sort': {
        name: '快速排序',
        description: '快速排序算法（Go版）',
        code: `// 快速排序算法
// 时间复杂度: 平均 O(n log n), 最坏 O(n²)
// 空间复杂度: O(log n)
package main

import "fmt"

func quickSort(arr []int, low, high int) []int {
	if low < high {
		pivotIndex := partition(arr, low, high)
		quickSort(arr, low, pivotIndex-1)
		quickSort(arr, pivotIndex+1, high)
	}
	return arr
}

func partition(arr []int, low, high int) int {
	pivot := arr[high]
	i := low - 1

	for j := low; j < high; j++ {
		if arr[j] <= pivot {
			i++
			arr[i], arr[j] = arr[j], arr[i]
		}
	}

	arr[i+1], arr[high] = arr[high], arr[i+1]
	return i + 1
}

func main() {
	arr := []int{64, 34, 25, 12, 22, 11, 90}
	fmt.Println("原数组:", arr)
	fmt.Println("排序后:", quickSort(arr, 0, len(arr)-1))
}`,
        confidence: 0.95
      },
      'binary-search': {
        name: '二分查找',
        description: '二分查找算法（Go版）',
        code: `// 二分查找算法
// 时间复杂度: O(log n)
package main

import "fmt"

func binarySearch(arr []int, target int) int {
	left, right := 0, len(arr)-1

	for left <= right {
		mid := (left + right) / 2

		if arr[mid] == target {
			return mid
		} else if arr[mid] < target {
			left = mid + 1
		} else {
			right = mid - 1
		}
	}

	return -1
}

func main() {
	sortedArr := []int{11, 12, 22, 25, 34, 64, 90}
	target := 25
	result := binarySearch(sortedArr, target)
	fmt.Printf("目标 %d 的索引: %d\\n", target, result)
}`,
        confidence: 0.95
      }
    },
    structure: {
      'class-template': {
        name: '结构体模板',
        description: 'Go 标准结构体模板',
        code: `// [类名] - [描述]
package main

import (
	"fmt"
	"sync"
)

// 默认配置
type Options struct {
	Option1 string
	Option2 int
}

func DefaultOptions() Options {
	return Options{
		Option1: "default",
		Option2: 0,
	}
}

// 主结构体
type Service struct {
	options Options
	mu      sync.RWMutex
}

func NewService(opts ...Options) *Service {
	opt := DefaultOptions()
	if len(opts) > 0 {
		opt = opts[0]
	}

	return &Service{
		options: opt,
	}
}

func (s *Service) Init() error {
	// 初始化逻辑
	return nil
}

func (s *Service) Process(data interface{}) (interface{}, error) {
	// 处理逻辑
	return data, nil
}

func (s *Service) Close() error {
	// 清理资源
	return nil
}

func main() {
	svc := NewService()
	defer svc.Close()

	if err := svc.Init(); err != nil {
		fmt.Println("初始化失败:", err)
		return
	}

	result, _ := svc.Process("test data")
	fmt.Println("结果:", result)
}`,
        confidence: 0.9
      }
    },
    network: {
      'http-server': {
        name: 'HTTP 服务器',
        description: 'Gin HTTP 服务器',
        code: `// HTTP 服务器 - Gin 框架
package main

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()

	// CORS 中间件
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// 健康检查
	r.GET("/api/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status":    "ok",
			"timestamp": time.Now().Unix(),
		})
	})

	// RESTful 路由示例
	r.GET("/api/items/:id", func(c *gin.Context) {
		id := c.Param("id")
		c.JSON(http.StatusOK, gin.H{
			"id": id,
		})
	})

	// 启动服务器
	r.Run(":8080")
}`,
        confidence: 0.9
      }
    },
    io: {
      'file-operations': {
        name: '文件操作',
        description: 'Go 文件操作',
        code: `// 文件操作工具
package main

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
)

// 读取文件
func ReadFile(filePath string) ([]byte, error) {
	return os.ReadFile(filePath)
}

// 写入文件
func WriteFile(filePath string, content []byte) error {
	dir := filepath.Dir(filePath)
	if err := os.MkdirAll(dir, 0755); err != nil {
		return err
	}
	return os.WriteFile(filePath, content, 0644)
}

// 检查文件是否存在
func FileExists(filePath string) bool {
	_, err := os.Stat(filePath)
	return err == nil
}

// 删除文件
func DeleteFile(filePath string) error {
	return os.Remove(filePath)
}

// 复制文件
func CopyFile(src, dst string) error {
	srcFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer srcFile.Close()

	dir := filepath.Dir(dst)
	if err := os.MkdirAll(dir, 0755); err != nil {
		return err
	}

	dstFile, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer dstFile.Close()

	_, err = io.Copy(dstFile, srcFile)
	return err
}

func main() {
	// 示例
	content := []byte("Hello, World!")

	if err := WriteFile("test.txt", content); err != nil {
		fmt.Println("写入失败:", err)
		return
	}

	data, err := ReadFile("test.txt")
	if err != nil {
		fmt.Println("读取失败:", err)
		return
	}

	fmt.Println("文件内容:", string(data))

	DeleteFile("test.txt")
}`,
        confidence: 0.9
      }
    }
  },

  // Rust 模板
  rust: {
    algorithm: {
      'quick-sort': {
        name: '快速排序',
        description: '快速排序算法（Rust版）',
        code: `// 快速排序算法
// 时间复杂度: 平均 O(n log n), 最坏 O(n²)
// 空间复杂度: O(log n)

fn partition<T: PartialOrd + Clone>(arr: &mut [T], low: usize, high: usize) -> usize {
    let pivot = arr[high].clone();
    let mut i = low.saturating_sub(1);

    for j in low..high {
        if arr[j] <= pivot {
            i += 1;
            arr.swap(i, j);
        }
    }

    arr.swap(i + 1, high);
    i + 1
}

fn quick_sort<T: PartialOrd + Clone>(arr: &mut [T], low: isize, high: isize) {
    if low < high {
        let pivot_index = partition(arr, low as usize, high as usize);
        let pivot_index = pivot_index as isize;

        quick_sort(arr, low, pivot_index - 1);
        quick_sort(arr, pivot_index + 1, high);
    }
}

fn main() {
    let mut arr = vec![64, 34, 25, 12, 22, 11, 90];
    println!("原数组: {:?}", arr);

    quick_sort(&mut arr, 0, (arr.len() - 1) as isize);
    println!("排序后: {:?}", arr);
}`,
        confidence: 0.95
      },
      'binary-search': {
        name: '二分查找',
        description: '二分查找算法（Rust版）',
        code: `// 二分查找算法
// 时间复杂度: O(log n)

fn binary_search<T: PartialOrd>(arr: &[T], target: &T) -> Option<usize> {
    let mut left = 0;
    let mut right = arr.len();

    while left < right {
        let mid = left + (right - left) / 2;

        if arr[mid] == *target {
            return Some(mid);
        } else if arr[mid] < *target {
            left = mid + 1;
        } else {
            right = mid;
        }
    }

    None
}

fn main() {
    let sorted_arr = vec![11, 12, 22, 25, 34, 64, 90];
    let target = 25;

    match binary_search(&sorted_arr, &target) {
        Some(index) => println!("目标 {} 的索引: {}", target, index),
        None => println!("未找到目标 {}", target),
    }
}`,
        confidence: 0.95
      }
    },
    structure: {
      'class-template': {
        name: '结构体模板',
        description: 'Rust 标准结构体模板',
        code: `// [类名] - [描述]
use std::sync::{Arc, RwLock};

/// 默认配置
#[derive(Debug, Clone)]
pub struct Options {
    pub option1: String,
    pub option2: i32,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            option1: "default".to_string(),
            option2: 0,
        }
    }
}

/// 主结构体
pub struct Service {
    options: Options,
    initialized: Arc<RwLock<bool>>,
}

impl Service {
    /// 创建新实例
    pub fn new(options: impl Into<Option<Options>>) -> Self {
        let options = options.into().unwrap_or_default();

        Self {
            options,
            initialized: Arc::new(RwLock::new(false)),
        }
    }

    /// 初始化
    pub fn init(&self) -> Result<(), String> {
        let mut initialized = self.initialized.write().map_err(|e| e.to_string())?;

        if *initialized {
            return Ok(());
        }

        // 初始化逻辑
        *initialized = true;
        Ok(())
    }

    /// 处理数据
    pub fn process<T: Clone>(&self, data: T) -> Result<T, String> {
        let initialized = self.initialized.read().map_err(|e| e.to_string())?;

        if !*initialized {
            return Err("Service not initialized".to_string());
        }

        Ok(data)
    }

    /// 关闭服务
    pub fn close(&self) {
        if let Ok(mut initialized) = self.initialized.write() {
            *initialized = false;
        }
    }
}

fn main() {
    let service = Service::new(None);

    if let Err(e) = service.init() {
        eprintln!("初始化失败: {}", e);
        return;
    }

    match service.process("test data") {
        Ok(result) => println!("结果: {:?}", result),
        Err(e) => eprintln!("处理失败: {}", e),
    }

    service.close();
}`,
        confidence: 0.9
      }
    },
    network: {
      'http-server': {
        name: 'HTTP 服务器',
        description: 'Actix-web HTTP 服务器',
        code: `// HTTP 服务器 - Actix-web 框架
use actix_web::{web, App, HttpServer, HttpResponse, HttpRequest, middleware};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// 健康检查响应
#[derive(Serialize)]
struct HealthResponse {
    status: String,
    timestamp: i64,
}

/// 健康检查端点
async fn health_check() -> HttpResponse {
    HttpResponse::Ok().json(HealthResponse {
        status: "ok".to_string(),
        timestamp: chrono::Utc::now().timestamp(),
    })
}

/// 获取项目端点
async fn get_item(path: web::Path<i32>) -> HttpResponse {
    HttpResponse::Ok().json(serde_json::json!({
        "id": path.into_inner(),
    }))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    println!("服务器启动在 http://127.0.0.1:8080");

    HttpServer::new(|| {
        App::new()
            // CORS 中间件
            .wrap(middleware::Logger::default())
            .wrap(
                middleware::DefaultHeaders::new()
                    .add(("Access-Control-Allow-Origin", "*"))
                    .add(("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"))
                    .add(("Access-Control-Allow-Headers", "Content-Type"))
            )
            // 路由
            .route("/api/health", web::get().to(health_check))
            .route("/api/items/{id}", web::get().to(get_item))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}`,
        confidence: 0.9
      }
    },
    io: {
      'file-operations': {
        name: '文件操作',
        description: 'Rust 文件操作',
        code: `// 文件操作工具
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::Path;

/// 读取文件
fn read_file(path: &Path) -> io::Result<String> {
    let mut file = File::open(path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents)
}

/// 写入文件
fn write_file(path: &Path, contents: &str) -> io::Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }

    let mut file = File::create(path)?;
    file.write_all(contents.as_bytes())?;
    Ok(())
}

/// 追加内容到文件
fn append_file(path: &Path, contents: &str) -> io::Result<()> {
    let mut file = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    file.write_all(contents.as_bytes())?;
    Ok(())
}

/// 检查文件是否存在
fn file_exists(path: &Path) -> bool {
    path.exists()
}

/// 删除文件
fn delete_file(path: &Path) -> io::Result<()> {
    fs::remove_file(path)
}

/// 复制文件
fn copy_file(src: &Path, dst: &Path) -> io::Result<()> {
    if let Some(parent) = dst.parent() {
        fs::create_dir_all(parent)?;
    }

    fs::copy(src, dst)?;
    Ok(())
}

fn main() {
    let test_path = Path::new("test.txt");

    // 示例
    match write_file(test_path, "Hello, World!") {
        Ok(_) => println!("写入成功"),
        Err(e) => eprintln!("写入失败: {}", e),
    }

    match read_file(test_path) {
        Ok(content) => println!("文件内容: {}", content),
        Err(e) => eprintln!("读取失败: {}", e),
    }

    let _ = delete_file(test_path);
}`,
        confidence: 0.9
      }
    }
  }
};

// ============================================================
// 语言检测模式
// ============================================================

const LANGUAGE_PATTERNS = {
  javascript: {
    keywords: ['javascript', 'js', 'node', 'nodejs', 'react', 'vue', 'angular'],
    extensions: ['.js', '.mjs', '.cjs'],
    patterns: ['function\\s+\\w+', 'const\\s+\\w+\\s*=', 'let\\s+\\w+\\s*=', 'require\\(', '=>']
  },
  typescript: {
    keywords: ['typescript', 'ts', 'tsconfig', '@types'],
    extensions: ['.ts', '.tsx'],
    patterns: ['interface\\s+\\w+', 'type\\s+\\w+\\s*=', ':\\s*(string|number|boolean|any)', 'export\\s+(class|interface|type)']
  },
  python: {
    keywords: ['python', 'py', 'pip', 'django', 'flask', 'fastapi', 'pandas', 'numpy'],
    extensions: ['.py', '.pyw'],
    patterns: ['def\\s+\\w+', 'import\\s+\\w+', 'class\\s+\\w+.*:', 'if\\s+__name__', 'print\\s*\\(']
  },
  bash: {
    keywords: ['bash', 'shell', 'sh', 'zsh', 'script'],
    extensions: ['.sh', '.bash'],
    patterns: ['#!/bin/bash', '#!/bin/sh', '\\$\\(', 'function\\s+\\w+\\s*\\(\\)', '\\$\\{?\\w+\\}?']
  },
  go: {
    keywords: ['golang', 'go', 'gin', 'goroutine'],
    extensions: ['.go'],
    patterns: ['package\\s+\\w+', 'func\\s+\\w+', 'import\\s*\\(', 'go\\s+\\w+', ':=']
  },
  rust: {
    keywords: ['rust', 'cargo', 'rustc', 'wasm'],
    extensions: ['.rs'],
    patterns: ['fn\\s+\\w+', 'let\\s+mut', 'impl\\s+\\w+', 'pub\\s+(fn|struct|enum)', 'use\\s+\\w+']
  }
};

const INTENT_PATTERNS = {
  algorithm: ['排序', '查找', '搜索', 'sort', 'search', 'sort', 'binary', 'quick', 'merge', 'bfs', 'dfs'],
  structure: ['类', '结构', '链表', '树', 'class', 'struct', 'list', 'tree', 'linked', 'array'],
  network: ['服务器', 'http', 'api', '请求', 'server', 'request', 'fetch', 'api', 'rest', 'endpoint'],
  io: ['文件', '读写', 'io', 'file', 'read', 'write', 'stream', 'buffer'],
  cli: ['命令行', 'cli', '命令', 'script', 'tool'],
  async: ['异步', '并发', '队列', 'async', 'promise', 'await', 'concurrency', 'queue', 'retry', 'timeout'],
  database: ['数据库', 'sql', '查询', '表', 'database', 'db', 'query', 'table', 'mongo', 'redis', '存储'],
  cache: ['缓存', 'cache', 'lru', 'ttl', 'memoize', 'memory', 'storage'],
  middleware: ['中间件', '拦截', 'middleware', 'interceptor', 'guard', 'rate', 'limiter', 'throttle']
};

// ============================================================
// 代码生成引擎主类
// ============================================================

class CodeGenerator {
  /**
   * 构造函数
   * @param {Object} options - 配置选项
   * @param {Object} options.hf - 心虫引擎引用
   */
  constructor({ hf } = {}) {
    this.hf = hf;
    this.templates = TEMPLATES;
    this.languagePatterns = LANGUAGE_PATTERNS;
    this.intentPatterns = INTENT_PATTERNS;

    // 统计信息
    this.stats = {
      templateHits: 0,
      llmHits: 0,
      totalGenerations: 0
    };
  }

  // ============================================================
  // 公开 API
  // ============================================================

  /**
   * 主生成方法
   * @param {string} task - 任务描述
   * @param {string} language - 目标语言
   * @param {Object} options - 选项
   * @returns {Promise<Object>} 生成结果
   */
  async generate(task, language = 'javascript', options = {}) {
    this.stats.totalGenerations++;

    // 1. 检测意图和语言
    const intent = this.detectIntent(task);
    const detectedLanguage = language === 'auto' ? intent.language : language;

    // 2. 验证语言支持
    if (!this.isLanguageSupported(detectedLanguage)) {
      return {
        success: false,
        error: `语言 "${detectedLanguage}" 不支持。支持的列表: ${this.getSupportedLanguages().join(', ')}`,
        code: null,
        language: null,
        filePath: null,
        metadata: null
      };
    }

    // 3. 尝试从本地模板获取
    const templateResult = this.findTemplate(detectedLanguage, intent.type, task);

    if (templateResult) {
      this.stats.templateHits++;
      return {
        success: true,
        code: templateResult.code,
        language: detectedLanguage,
        filePath: null,
        metadata: {
          source: 'template',
          templateName: templateResult.name,
          confidence: templateResult.confidence,
          intent: intent,
          llmUsed: false
        }
      };
    }

    // 4. 回退到 LLM 生成
    this.stats.llmHits++;
    return await this._generateWithLLM(task, detectedLanguage, intent, options);
  }

  /**
   * 生成并输出到文件
   * @param {string} task - 任务描述
   * @param {string} filePath - 输出文件路径
   * @param {Object} options - 选项
   * @returns {Promise<Object>} 生成结果
   */
  async generateFile(task, filePath, options = {}) {
    // 检测语言
    const ext = path.extname(filePath).toLowerCase();
    const language = this._detectLanguageFromExtension(ext);

    // 生成代码
    const result = await this.generate(task, language, options);

    if (!result.success) {
      return result;
    }

    // 写入文件
    try {
      const fs = require('fs');
      const dir = path.dirname(filePath);

      // 确保目录存在
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
      }

      fs.writeFileSync(filePath, result.code, 'utf-8');

      // 更新返回值
      result.filePath = filePath;
      result.metadata.filePath = filePath;

      // 记录到记忆系统
      await this._recordGeneration(task, result);

      return result;
    } catch (err) {
      return {
        success: false,
        error: `写入文件失败: ${err.message}`,
        code: result.code,
        language: result.language,
        filePath: null,
        metadata: result.metadata
      };
    }
  }

  /**
   * 识别语言和意图
   * @param {string} text - 输入文本
   * @returns {Object} 识别结果
   */
  detectIntent(text) {
    const lowerText = text.toLowerCase();
    const result = {
      language: null,
      type: null,
      confidence: 0,
      keywords: [],
      raw: text
    };

    // 检测语言
    for (const [lang, pattern] of Object.entries(this.languagePatterns)) {
      let langScore = 0;

      // 关键词匹配
      for (const keyword of pattern.keywords) {
        if (lowerText.includes(keyword)) {
          langScore += 0.3;
          result.keywords.push(keyword);
        }
      }

      // 扩展名匹配
      for (const ext of pattern.extensions) {
        if (lowerText.includes(ext)) {
          langScore += 0.4;
        }
      }

      // 代码模式匹配
      for (const pat of pattern.patterns) {
        const regex = new RegExp(pat, 'i');
        if (regex.test(text)) {
          langScore += 0.2;
        }
      }

      if (langScore > result.confidence) {
        result.confidence = langScore;
        result.language = lang;
      }
    }

    // 默认语言
    if (!result.language || result.confidence < 0.2) {
      result.language = 'javascript';
      result.confidence = 0.5;
    }

    // 检测意图类型
    for (const [type, keywords] of Object.entries(this.intentPatterns)) {
      for (const keyword of keywords) {
        if (lowerText.includes(keyword.toLowerCase())) {
          result.type = type;
          break;
        }
      }
      if (result.type) break;
    }

    // 默认类型
    if (!result.type) {
      result.type = this._guessIntentType(text);
    }

    return result;
  }

  /**
   * 返回可用模板列表
   * @returns {Object} 按语言和类型组织的模板列表
   */
  getAvailableTemplates() {
    const result = {};

    for (const [lang, categories] of Object.entries(this.templates)) {
      result[lang] = {};

      for (const [category, templates] of Object.entries(categories)) {
        result[lang][category] = Object.entries(templates).map(([key, tmpl]) => ({
          id: key,
          name: tmpl.name,
          description: tmpl.description,
          confidence: tmpl.confidence
        }));
      }
    }

    return result;
  }

  /**
   * 获取支持的编程语言列表
   * @returns {string[]} 语言列表
   */
  getSupportedLanguages() {
    return Object.keys(this.templates);
  }

  /**
   * 检查语言是否支持
   * @param {string} language - 语言名
   * @returns {boolean} 是否支持
   */
  isLanguageSupported(language) {
    return language in this.templates;
  }

  /**
   * 获取生成统计
   * @returns {Object} 统计信息
   */
  getStats() {
    return {
      ...this.stats,
      templateHitRate: this.stats.totalGenerations > 0
        ? (this.stats.templateHits / this.stats.totalGenerations * 100).toFixed(1) + '%'
        : '0%'
    };
  }

  // ============================================================
  // 私有方法
  // ============================================================

  /**
   * 查找本地模板
   * @private
   */
  findTemplate(language, intentType, task) {
    const templates = this.templates[language];
    if (!templates) return null;

    const lowerTask = task.toLowerCase();

    // 首先按意图类型查找
    if (intentType && templates[intentType]) {
      const categoryTemplates = templates[intentType];

      for (const [key, tmpl] of Object.entries(categoryTemplates)) {
        // 检查模板名或描述是否匹配任务
        if (lowerTask.includes(tmpl.name.toLowerCase()) ||
            lowerTask.includes(tmpl.description.toLowerCase()) ||
            key.includes(lowerTask.replace(/\s+/g, '-'))) {
          return tmpl;
        }
      }

      // 返回第一个作为默认
      return Object.values(categoryTemplates)[0];
    }

    // 在所有类别中搜索
    for (const category of Object.keys(templates)) {
      for (const [key, tmpl] of Object.entries(templates[category])) {
        if (lowerTask.includes(tmpl.name.toLowerCase()) ||
            lowerTask.includes(tmpl.description.toLowerCase())) {
          return tmpl;
        }
      }
    }

    return null;
  }

  /**
   * 使用 LLM 生成代码
   * @private
   */
  async _generateWithLLM(task, language, intent, options = {}) {
    const prompt = this._buildLLMPrompt(task, language, intent);

    try {
      let code = null;

      // 优先尝试 hf.dispatch
      if (this.hf && typeof this.hf.dispatch === 'function') {
        const response = await this.hf.dispatch('generate', { task, language, intent, options });
        if (response && response.code) {
          code = response.code;
        }
      }

      // 回退到 _llmClient
      if (!code && this.hf && this.hf._llmClient) {
        const response = await this.hf._llmClient.generate(prompt);
        if (response && response.text) {
          code = this._extractCode(response.text);
        }
      }

      // 最后回退到直接调用
      if (!code && this.hf && typeof this.hf.generate === 'function') {
        const response = await this.hf.generate(prompt);
        if (response) {
          code = typeof response === 'string' ? response : response.code || response.text;
        }
      }

      if (code) {
        return {
          success: true,
          code: code,
          language: language,
          filePath: null,
          metadata: {
            source: 'llm',
            intent: intent,
            llmUsed: true,
            prompt: prompt.substring(0, 100) + '...'
          }
        };
      }

      return {
        success: false,
        error: 'LLM 生成失败：无法获取代码生成结果',
        code: null,
        language: language,
        filePath: null,
        metadata: null
      };
    } catch (err) {
      return {
        success: false,
        error: `LLM 生成失败: ${err.message}`,
        code: null,
        language: language,
        filePath: null,
        metadata: null
      };
    }
  }

  /**
   * 构建 LLM 提示词
   * @private
   */
  _buildLLMPrompt(task, language, intent) {
    return `请为以下任务生成 ${language} 代码：

任务描述: ${task}
目标语言: ${language}
代码类型: ${intent.type || '通用'}

要求：
1. 生成完整可运行的代码
2. 添加必要的注释说明
3. 遵循 ${language} 最佳实践
4. 如果有多种实现方式，提供最优方案

请直接输出代码，不需要额外的解释。`;
  }

  /**
   * 从 LLM 输出中提取代码
   * @private
   */
  _extractCode(text) {
    // 尝试提取 ``` 包裹的代码块
    const codeBlockMatch = text.match(/```(?:\w+)?\n([\s\S]*?)```/);
    if (codeBlockMatch) {
      return codeBlockMatch[1].trim();
    }

    // 如果没有代码块，尝试找到明显的代码开始
    const lines = text.split('\n');
    const codeStart = lines.findIndex(line => {
      const trimmed = line.trim();
      return trimmed.startsWith('function ') ||
             trimmed.startsWith('class ') ||
             trimmed.startsWith('def ') ||
             trimmed.startsWith('fn ') ||
             trimmed.startsWith('import ') ||
             trimmed.startsWith('package ') ||
             trimmed.startsWith('#!/');
    });

    if (codeStart !== -1) {
      return lines.slice(codeStart).join('\n');
    }

    // 返回原始文本
    return text.trim();
  }

  /**
   * 根据扩展名检测语言
   * @private
   */
  _detectLanguageFromExtension(ext) {
    const extMap = {
      '.js': 'javascript',
      '.mjs': 'javascript',
      '.cjs': 'javascript',
      '.ts': 'typescript',
      '.tsx': 'typescript',
      '.py': 'python',
      '.pyw': 'python',
      '.sh': 'bash',
      '.bash': 'bash',
      '.go': 'go',
      '.rs': 'rust'
    };

    return extMap[ext] || 'javascript';
  }

  /**
   * 猜测意图类型
   * @private
   */
  _guessIntentType(text) {
    const lowerText = text.toLowerCase();

    // 基于关键词模式猜测
    if (/algorithm|排序|查找|搜索|sorter|binary/.test(lowerText)) {
      return 'algorithm';
    }
    if (/server|http|api|请求|endpoint/.test(lowerText)) {
      return 'network';
    }
    if (/file|文件|读写|read|write/.test(lowerText)) {
      return 'io';
    }
    if (/class|struct|结构|链表|tree/.test(lowerText)) {
      return 'structure';
    }

    return 'algorithm'; // 默认类型
  }

  /**
   * 记录生成结果到记忆系统
   * @private
   */
  async _recordGeneration(task, result) {
    if (!this.hf || !this.hf.meaningfulMemory) return;

    try {
      await this.hf.meaningfulMemory.remember(
        `code-gen:${Date.now()}`,
        {
          task: task,
          language: result.language,
          template: result.metadata?.templateName || 'llm',
          success: result.success,
          timestamp: new Date().toISOString()
        },
        'ephemeral'
      );
    } catch (err) {
      // 静默失败，不影响主流程
      console.warn('记录生成结果失败:', err.message);
    }
  }
}

// ============================================================
// 导出
// ============================================================

module.exports = { CodeGenerator, TEMPLATES };