#!/bin/bash

set -e

# Parse command line parameters
WORKING_DIR="docs"
for arg in "$@"; do
    case $arg in
        --working-dir=*)
            WORKING_DIR="${arg#*=}"
            shift
            ;;
    esac
done
export CLAUDEFSD_WORKING_DIR="$WORKING_DIR"

# Check dependencies
$(dirname "$0")/claudefsd-check-dependencies

mkdir -p logs

# Use a temporary directory for tmp files
mkdir -p tmp
export TMPDIR=tmp/

# look for required files (prefer $WORKING_DIR/BRIEF.md, fallback to BRIEF.md)
source "$(dirname "$0")/claudefsd-find-brief"
BRIEF_FILE=$(find_brief_file)
if [ $? -ne 0 ]; then
    echo "No BRIEF.md file found in $WORKING_DIR/ or root directory, please create one first"
    exit 1
fi

# Check for required input files using flexible detection
questions_file=$(find_project_file "QUESTIONS.md" 2>/dev/null || echo "")
requirements_file=$(find_project_file "REQUIREMENTS.md" 2>/dev/null || echo "")

if [ -z "$questions_file" ] && [ -z "$requirements_file" ]; then
    echo "No QUESTIONS.md or REQUIREMENTS.md found in $WORKING_DIR/ or root directory."
    echo "Please run either:"
    echo "  - 'claudefsd analyze-brief' to generate questions, or"
    echo "  - 'claudefsd interview' to conduct an interactive interview"
    exit 1
fi

LOGFILE="logs/claude-$(date +%Y%m%d_%H%M%S).txt"

echo -e "\033[32m==================================================================\033[0m"
echo -e "\033[32m== CREATING PLAN FROM PROJECT INPUTS\033[0m"
echo -e "\033[32m==================================================================\033[0m"

# Build list of files to read (using flexible paths)
plan_file=$(find_project_file "PLAN.md" 2>/dev/null || echo "")
notes_file=$(find_project_file "CLAUDE-NOTES.md" 2>/dev/null || echo "")
ideas_file=$(find_project_file "IDEAS.md" 2>/dev/null || echo "")
webtests_file=$(find_project_file "WEBTESTS.md" 2>/dev/null || echo "")
readme_file=$(find_project_file "README.md" 2>/dev/null || echo "")

# Build file list for prompt
file_list="- $BRIEF_FILE -- the project brief"
[ -n "$questions_file" ] && file_list="$file_list
- $questions_file -- the project questions (with answers) from analyze-brief or interview"
[ -n "$requirements_file" ] && file_list="$file_list
- $requirements_file -- consolidated requirements from interview process"
[ -n "$notes_file" ] && file_list="$file_list
- $notes_file -- AI's working notes and understanding"
[ -n "$plan_file" ] && file_list="$file_list
- $plan_file -- the project plan"
[ -n "$ideas_file" ] && file_list="$file_list
- $ideas_file -- the backlog of future ideas"
[ -n "$webtests_file" ] && file_list="$file_list
- $webtests_file -- the project web tests"
[ -n "$readme_file" ] && file_list="$file_list
- $readme_file -- the project README"

# Determine output paths (prefer working dir if it exists, otherwise root)
if [ -d "$WORKING_DIR" ] && [ "$WORKING_DIR" != "." ]; then
    output_notes="$WORKING_DIR/CLAUDE-NOTES.md"
    output_plan="$WORKING_DIR/PLAN.md"
else
    output_notes="CLAUDE-NOTES.md"
    output_plan="PLAN.md"
fi

    prompt2="
Read and analyze these project files if they exist:
$file_list

Your job, as a megathinking architect and project manager, is to create the project plan and working notes.

1. Read through the BRIEF.md and any available requirements/questions.
2. Update or create $output_notes with your interpretation and understanding of the project.
3. Update or create $output_plan with a detailed implementation plan based on all available inputs.

The CLAUDE-NOTES.md should contain:
- Your understanding of the project goals and requirements
- Key technical decisions and rationale
- Important assumptions and constraints
- Areas that may need future clarification

The PLAN.md should contain:
- Master plan limited to 100 lines maximum
- High-level sections with [ ] checkboxes for completion tracking
- For complex projects, reference detailed sub-plans in separate files (plan-section1.md, plan-section2.md, etc.)
- Include proportional infrastructure setup (basic linting + pre-commit hooks)
- Group related tasks into logical phases
- If the plan would exceed 100 lines, create a master plan with section references and detailed sub-plans

INFRASTRUCTURE PROPORTIONALITY RULES:
- Basic linter + pre-commit hooks: Always include for any project
- Tests: Should be ≤50% the size of functional code (not 3x larger!)
- For simple shell scripts (~200-500 lines): Basic integration tests only
- For complex systems (>1000 lines): More comprehensive testing
- NO enterprise patterns for simple solutions (file locking, complex CI, monolithic architectures)
- Follow existing claude-fsd pattern: separate focused scripts, not monoliths
- FAIL LOUD - simple error handling, exit on failure
- Choose infrastructure complexity appropriate to solution size
"

# Add ultrathink instruction to the beginning
ultrathink_instruction="<ultrathink>
You are entering deep strategic planning mode. Before responding, engage in extended reasoning to:
- Analyze the full scope and implications of the project
- Consider architectural tradeoffs and long-term consequences
- Identify edge cases, failure modes, and technical risks
- Think through the optimal approach from multiple angles
Take your time to think deeply about the best solution before generating your plan.
</ultrathink>

"

# Prepend ultrathink to the prompt
prompt2="$ultrathink_instruction$prompt2"

# Run planning with opus + ultrathink
echo "Running claude with opus model (ultrathink mode)..."
claude --model opus --dangerously-skip-permissions -p "$prompt2" | tee >(cat > $LOGFILE-ba3)

echo -e "\033[32m==================================================================\033[0m"
echo -e "\033[32m== PLAN CREATION COMPLETE\033[0m"
echo -e "\033[32m==================================================================\033[0m"
echo "Plan created in $output_plan"
echo "Working notes saved in $output_notes"
echo "You can now run 'claudefsd dev' to start the development process."



