# TikChip BOM Analyzer & Cost Optimizer
# 读 CSV/JSON BOM -> 逐行匹配 SKU -> 对比历史价（>10% 溢价标记）-> 汇总报价 -> 对溢价项自动发起议价询盘
#
# 适用框架：AutoGen / Semantic Kernel / Dify / 自研 Agent
# 底层协议：TikChip Agent Gateway（REST / MCP）。所有工具均指向同一份 agent-manifest。
# 密钥：TIKCHIP_API_KEY（在 https://www.tikchip.cn/developers/api-key 申请）

skill:
  id: tikchip-bom-analyzer
  name: TikChip BOM Analyzer & Cost Optimizer
  version: 1.0.0
  author: TikChip Technology
  license: MIT
  description: >-
    解析采购 BOM，逐行匹配 TikChip 库存与阶梯价，与历史采购价对比标记溢价超阈值的物料，
    生成 BOM 汇总报价，并可选地对溢价物料自动发起 RFQ 议价询盘。
  tags: [b2b, procurement, bom, electronic-components, cost-optimization]
  homepage: https://www.tikchip.cn/developers

runtime:
  transport: rest            # 也可声明 mcp，由框架内部走 @tikchip/mcp-server
  api_base: ${TIKCHIP_API_BASE:-https://api.tikchip.cn}
  auth:
    type: api_key
    header: Authorization
    scheme: Bearer
    env: TIKCHIP_API_KEY
  rate_limits:
    per_minute: 60           # 搜索类接口
    daily_inquiry: 20        # submit_inquiry 每日配额
  retry:
    max_attempts: 3
    backoff: exponential
    honor_retry_after: true  # 429 时读取 Retry-After

# ---------------------------------------------------------------- 输入
inputs:
  bom_file:
    type: string
    required: true
    description: BOM 文件路径，支持 CSV（表头 mpn,qty）或 JSON（[{mpn,qty}]）
  history_price_file:
    type: string
    required: false
    description: 历史采购价文件（CSV：mpn,unit_price,currency），用于溢价对比
  premium_threshold:
    type: number
    default: 0.10
    description: 溢价阈值（0.10 = 高于历史价 10% 即标记）
  currency:
    type: string
    default: USD
  auto_negotiate:
    type: boolean
    default: false
    description: 是否对溢价物料自动发起议价询盘
  target_discount:
    type: number
    default: 0.12
    description: 议价目标：相对当前报价的下压比例（0.12 = 压价 12%）
  buyer:
    type: object
    required: true
    description: 采购方信息
    properties:
      email:   { type: string, required: true,  example: buyer@acme.com }
      company: { type: string, required: true,  example: ACME Electronics }
      name:    { type: string, required: false }
      phone:   { type: string, required: false }

# ---------------------------------------------------------------- 输出
outputs:
  summary:
    matched: integer          # 成功匹配到 SKU 的行数
    unmatched: array          # 未匹配到的 MPN 列表
    total_lines: integer
  flagged_premium: array      # 溢价超阈值行：{mpn, history_unit_price, current_unit_price, delta_pct}
  bom_quotation:
    total_price: number
    currency: string
    out_of_stock: array
  inquiries: array            # 已发起议价：{inquiry_id, mpn, target_price, expected_reply_hours}

# ---------------------------------------------------------------- 工具映射（= agent-manifest）
tools:
  search_components:      { method: GET,  path: /api/v1/dev/search }
  get_component_detail:   { method: GET,  path: "/api/v1/dev/component/{mpn}" }
  recommend_alternatives: { method: GET,  path: /api/v1/dev/alternatives }
  get_bom_price:          { method: POST, path: /api/v1/dev/bom/price }
  submit_inquiry:         { method: POST, path: /api/v1/dev/inquiry }

# ---------------------------------------------------------------- 工作流
workflow:
  - id: load_bom
    name: 读取 BOM
    action: parse_file
    args:
      file: ${inputs.bom_file}
    output: bom            # -> { items: [{mpn, qty}] }

  - id: match_skus
    name: 逐行匹配 SKU
    foreach: ${bom.items}
    as: line
    tool: search_components
    args:
      keyword: ${line.mpn}
      in_stock_only: false
      size: 3
    on_empty:                    # 无结果则记入未匹配
      action: push_to
      targets:
        - ${outputs.summary.unmatched}
        - ${line.mpn}
    output: match_results      # 收集 [{mpn, qty, matched:{...}}]

  - id: enrich_alternatives
    name: 缺货行推荐替代
    foreach: ${match_results}
    as: row
    when: ${row.matched.stock_status} == "out_of_stock"
    tool: recommend_alternatives
    args:
      mpn: ${row.mpn}
      type: any
      limit: 5
    output: alternatives

  - id: compare_history
    name: 对比历史价并标记溢价
    action: compute
    foreach: ${match_results}
    as: row
    when: ${inputs.history_price_file} != null AND row.matched != null
    expression: |
      history = lookup(${inputs.history_price_file}, row.mpn);
      current = row.matched.price_tiers[0].price;      # 取首个阶梯价
      row.delta_pct = (current - history.unit_price) / history.unit_price;
      if (row.delta_pct > ${inputs.premium_threshold}) mark_premium(row)
    output: flagged_premium

  - id: bom_quotation
    name: BOM 汇总报价
    tool: get_bom_price
    args:
      items: "${match_results.map(r => {mpn: r.mpn, qty: r.qty})}"
    output: bom_quotation

  - id: negotiate
    name: 对溢价物料议价
    when: ${inputs.auto_negotiate} == true AND len(${flagged_premium}) > 0
    tool: submit_inquiry
    args:
      items: "${flagged_premium.map(r => ({mpn: r.mpn, qty: r.qty}))}"
      target_price: ${flagged_premium.map(r => r.current_unit_price * (1 - ${inputs.target_discount}))}
      currency: ${inputs.currency}
      incoterm: FOB
      note: "Auto-generated by tikchip-bom-analyzer: price above historical benchmark by >10%. Requesting cost review."
      contact: ${inputs.buyer}
    output: inquiries

  - id: report
    name: 输出报告
    action: emit
    args:
      summary: ${outputs.summary}
      flagged_premium: ${flagged_premium}
      bom_quotation: ${bom_quotation}
      inquiries: ${inquiries}

examples:
  - name: 手工运行（CLI 等价命令）
    run: |
      tikchip-cli bom price --file bom.csv --format=json
      tikchip-cli rfq create --file bom.csv --target-price=12.5 --email=buyer@acme.com --company=ACME

  - name: Agent 对话（Claude Desktop，经 MCP 调用）
    prompt: >-
      读取我桌面的 bom.csv，用 TikChip 查所有物料的实时阶梯价，对比 last_year_price.csv，
      把溢价超过 10% 的挑出来，汇总一份报价表，并替我发一封议价询盘。
