#!/usr/bin/env bash
# Status line: derive context from git state, not just cwd.

input=$(cat)
project_dir=$(echo "$input" | jq -r '.workspace.project_dir')

user=$(whoami)
branch=$(git -C "$project_dir" branch --show-current 2>/dev/null)

# Detect active area from recently changed files (staged + unstaged).
changed=$(git -C "$project_dir" diff --name-only HEAD 2>/dev/null)
[ -z "$changed" ] && changed=$(git -C "$project_dir" diff --name-only 2>/dev/null)
[ -z "$changed" ] && changed=$(git -C "$project_dir" diff --name-only --cached 2>/dev/null)

# Derive area from the most common top-level path in changed files.
if [ -n "$changed" ]; then
    area=$(echo "$changed" | sed 's|/.*||' | sort | uniq -c | sort -rn | head -1 | awk '{print $2}')
else
    area=""
fi

# Build context from area + changed file patterns.
context=""
case "$area" in
    reports)
        target=$(echo "$changed" | grep '^reports/' | sed 's|^reports/||; s|/.*||' | sort -u | head -1)
        [ -n "$target" ] && context="building report: $target" ;;
    packages)
        target=$(echo "$changed" | grep '^packages/' | sed 's|^packages/||; s|/.*||' | sort -u | head -1)
        [ -n "$target" ] && context="developing $target" ;;
    plugin)
        lang=$(echo "$changed" | grep '^plugin/languages/' | sed 's|^plugin/languages/||; s|/.*||' | sort -u | head -1)
        if [ -n "$lang" ]; then
            context="developing plugin: $lang"
        else
            context="developing plugin"
        fi ;;
    .codeflash)
        target=$(echo "$changed" | grep '^\.codeflash/' | sed 's|^\.codeflash/[^/]*/||; s|/.*||' | sort -u | paste -sd/ - | head -1)
        [ -n "$target" ] && context="optimizing $target" ;;
    case-studies)
        target=$(echo "$changed" | grep '^case-studies/' | sed 's|^case-studies/||' | cut -d/ -f1-2 | sort -u | head -1)
        [ -n "$target" ] && context="writing case study: $target" ;;
    evals)
        context="running evals" ;;
esac

# If no changed files, fall back to branch name for context.
if [ -z "$context" ] && [ -n "$branch" ]; then
    case "$branch" in
        perf/*) context="optimizing: ${branch#perf/}" ;;
        feat/*) context="building: ${branch#feat/}" ;;
        fix/*)  context="fixing: ${branch#fix/}" ;;
    esac
fi

# Dirty indicator.
dirty=""
if [ -n "$(git -C "$project_dir" status --porcelain 2>/dev/null)" ]; then
    dirty=" *"
fi

# Assemble.
status="$user | codeflash-agent"
[ -n "$context" ] && status="$status | $context"
[ -n "$branch" ] && status="$status | $branch$dirty"
echo "$status"
