# CSV/TSV processing: inline data, exec stdout, RESOURCES, filtering, encoding, mail attachment

flowmarkup:
  title: CSV Processing Demo
  version: 1
  description: Demonstrates CSV/TSV as compound shorthands — inline data, exec auto-decode, RESOURCES, row iteration, filtering, encode, and email attachment

  requires:
    EXEC:
    - csvtool
    MAIL: ["@example.com"]
    RESOURCES:
      report_data: {}

  input:
    recipient: EMAIL
    min_score:
      $kind: NUMBER
      $default: 50

  output:
    summary: STRING

  vars:
    team_roster:
      $kind: CSV
      $value: |
        name,email,role
        alice,alice@example.com,admin
        bob,bob@example.com,viewer
        carol,carol@example.com,editor

  do:
  # 1. Iterate inline CSV rows
  - forEach:
      items: =team_roster
      as: member
      maxItems: 10000
      do:
      - log: "Team member: {{member.name}} ({{member.role}})"

  # 2. CSV from exec stdout — auto-decoded to list of maps
  - exec:
      command: csvtool
      args:
      - =RESOURCES.report_data
      parseAs: CSV
      timeout: 60s
      result: {exam_results: =RESULT.stdout}

  # 3. Filter rows by score threshold
  - set:
      high_scorers: =exam_results.filter(r, int(r.score) >= min_score)

  - log: "=size(high_scorers) + ' students scored above ' + min_score"

  # 4. Iterate filtered results
  - forEach:
      items: =high_scorers
      as: student
      maxItems: 10000
      do:
      - log: "High scorer: {{student.name}} — {{student.score}}"

  # 5. Encode back to CSV/TSV text
  - set:
      csv_text: =high_scorers.encode(CSV)
      tsv_text: =high_scorers.encode(TSV)

  - log: "CSV output:\n{{csv_text}}"

  # 6. Send filtered results as CSV email attachment
  - mail:
      to: =recipient
      subject: "High Scorers Report"
      body: "Attached are students scoring above {{min_score}}."
      attachments:
      - data: =csv_text
        name: high-scorers.csv
      timeout: 30s

  - return:
      summary: "='Processed ' + size(exam_results) + ' rows, ' + size(high_scorers) + ' above threshold'"
