#!/bin/bash
# autoworkflow.sh
# AutoWorkflow CLI Orchestrator
# Usage: ./scripts/autoworkflow.sh [command] [options]

set -o pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

# Configuration
MAX_FIX_ATTEMPTS=10

cd "$PROJECT_ROOT"

print_header() {
    echo ""
    echo -e "${CYAN}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${CYAN}║              AUTOWORKFLOW SYSTEM                             ║${NC}"
    echo -e "${CYAN}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

print_phase() {
    local phase="$1"
    echo ""
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${BLUE}  PHASE: $phase${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
}

# ─────────────────────────────────────────────────────────────
# VERIFICATION
# ─────────────────────────────────────────────────────────────

run_verification() {
    print_phase "VERIFICATION"

    local has_errors=0

    # TypeScript check
    echo "📋 Running TypeScript check..."
    if npm run typecheck 2>&1; then
        echo -e "${GREEN}✓ TypeScript: No errors${NC}"
    else
        echo -e "${RED}✗ TypeScript: Errors found${NC}"
        has_errors=1
    fi

    echo ""

    # ESLint check
    echo "📋 Running ESLint check..."
    if npm run lint 2>&1; then
        echo -e "${GREEN}✓ ESLint: No warnings${NC}"
    else
        echo -e "${RED}✗ ESLint: Warnings/errors found${NC}"
        has_errors=1
    fi

    echo ""

    if [ $has_errors -eq 0 ]; then
        echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${GREEN}✅ VERIFICATION PASSED${NC}"
        echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        return 0
    else
        echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${RED}❌ VERIFICATION FAILED${NC}"
        echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        return 1
    fi
}

# ─────────────────────────────────────────────────────────────
# AUDIT
# ─────────────────────────────────────────────────────────────

run_audit() {
    print_phase "AUDIT"

    local has_issues=0

    # UI Enforcement check
    echo "🔍 Running UI enforcement check..."
    if [ -f "./scripts/check-ui-enforcement.sh" ]; then
        if ./scripts/check-ui-enforcement.sh 2>&1; then
            echo -e "${GREEN}✓ UI Enforcement: No orphan features${NC}"
        else
            echo -e "${RED}✗ UI Enforcement: Orphan features found${NC}"
            has_issues=1
        fi
    else
        echo -e "${YELLOW}⚠ UI Enforcement: Script not found, skipping${NC}"
    fi

    echo ""

    # Circular dependency check
    echo "🔍 Running circular dependency check..."
    if command -v npx &> /dev/null && [ -d "src" ]; then
        CYCLES=$(npx madge --circular --extensions ts,tsx src/ 2>/dev/null)
        if [ -z "$CYCLES" ] || [[ "$CYCLES" == *"No circular"* ]]; then
            echo -e "${GREEN}✓ Circular Deps: No cycles detected${NC}"
        else
            echo -e "${RED}✗ Circular Deps: Cycles found${NC}"
            echo "$CYCLES"
            has_issues=1
        fi
    else
        echo -e "${YELLOW}⚠ Circular Deps: madge not available or no src/, skipping${NC}"
    fi

    echo ""

    if [ $has_issues -eq 0 ]; then
        echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${GREEN}✅ AUDIT PASSED${NC}"
        echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        return 0
    else
        echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${RED}❌ AUDIT FAILED${NC}"
        echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        return 1
    fi
}

# ─────────────────────────────────────────────────────────────
# PRE-COMMIT CHECK
# ─────────────────────────────────────────────────────────────

run_precommit_check() {
    print_phase "PRE-COMMIT CHECK"

    local has_issues=0

    # Check for TODO/FIXME
    echo "🔍 Checking for TODO/FIXME comments..."
    if git diff --cached --name-only 2>/dev/null | xargs grep -l "TODO\|FIXME\|XXX\|HACK" 2>/dev/null; then
        echo -e "${RED}✗ Found TODO/FIXME comments in staged files${NC}"
        has_issues=1
    else
        echo -e "${GREEN}✓ No TODO/FIXME comments${NC}"
    fi

    # Check for console.log
    echo "🔍 Checking for console.log statements..."
    if git diff --cached --name-only 2>/dev/null | xargs grep -l "console\.\(log\|debug\|info\)" 2>/dev/null; then
        echo -e "${RED}✗ Found console.log statements in staged files${NC}"
        has_issues=1
    else
        echo -e "${GREEN}✓ No console.log statements${NC}"
    fi

    echo ""

    if [ $has_issues -eq 0 ]; then
        echo -e "${GREEN}✓ Pre-commit checks passed${NC}"
        return 0
    else
        echo -e "${RED}✗ Pre-commit checks failed${NC}"
        return 1
    fi
}

# ─────────────────────────────────────────────────────────────
# COMMIT
# ─────────────────────────────────────────────────────────────

run_commit() {
    local msg="${1:-"chore: update"}"

    print_phase "COMMIT"

    # Check for changes
    if git diff --quiet && git diff --staged --quiet; then
        echo -e "${YELLOW}⚠️  No changes to commit${NC}"
        return 0
    fi

    # Run verification first
    if ! run_verification; then
        echo -e "${RED}❌ Cannot commit: verification failed${NC}"
        return 1
    fi

    # Run pre-commit checks
    if ! run_precommit_check; then
        echo -e "${RED}❌ Cannot commit: pre-commit checks failed${NC}"
        return 1
    fi

    # Stage and commit
    echo ""
    echo "📝 Staging changes..."
    git add -A

    echo ""
    echo "Files to be committed:"
    git diff --staged --name-only | head -20

    echo ""
    echo "💾 Committing..."
    git commit -m "$msg"

    COMMIT_HASH=$(git rev-parse --short HEAD)

    echo ""
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}✅ COMMIT SUCCESSFUL: $COMMIT_HASH${NC}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

    return 0
}

# ─────────────────────────────────────────────────────────────
# FULL WORKFLOW
# ─────────────────────────────────────────────────────────────

run_full_workflow() {
    local commit_msg="${1:-"feat: implement feature"}"

    print_header

    echo "Starting full workflow..."
    echo "Commit message: $commit_msg"

    # Step 1: Verify
    if ! run_verification; then
        echo ""
        echo -e "${YELLOW}⚠️  Verification failed. Fix errors and try again.${NC}"
        return 1
    fi

    # Step 2: Audit
    if ! run_audit; then
        echo ""
        echo -e "${YELLOW}⚠️  Audit failed. Fix issues and try again.${NC}"
        return 1
    fi

    # Step 3: Commit
    run_commit "$commit_msg"

    echo ""
    echo -e "${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║                    WORKFLOW COMPLETE                          ║${NC}"
    echo -e "${GREEN}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

# ─────────────────────────────────────────────────────────────
# STATUS
# ─────────────────────────────────────────────────────────────

show_status() {
    print_header
    print_phase "STATUS"

    echo "📁 Git Status:"
    git status --short 2>/dev/null || echo "  Not a git repository"
    echo ""

    echo "📜 Recent Commits:"
    git log --oneline -5 2>/dev/null || echo "  No commits yet"
    echo ""

    echo "🔍 Verification Status:"
    run_verification || true
}

# ─────────────────────────────────────────────────────────────
# MAIN
# ─────────────────────────────────────────────────────────────

case "${1:-help}" in
    verify)
        print_header
        run_verification
        ;;
    audit)
        print_header
        run_audit
        ;;
    commit)
        run_commit "${2:-"chore: update"}"
        ;;
    full)
        run_full_workflow "${2:-"feat: implement feature"}"
        ;;
    status)
        show_status
        ;;
    help|*)
        echo "AutoWorkflow CLI"
        echo ""
        echo "Usage: $0 <command> [options]"
        echo ""
        echo "Commands:"
        echo "  status          Show current status"
        echo "  verify          Run TypeScript + ESLint verification"
        echo "  audit           Run UI enforcement + circular deps check"
        echo "  commit \"msg\"    Verify and commit with message"
        echo "  full \"msg\"      Full workflow (verify → audit → commit)"
        echo ""
        echo "Examples:"
        echo "  $0 status"
        echo "  $0 verify"
        echo "  $0 commit \"feat: add login page\""
        echo "  $0 full \"feat: add user profile\""
        echo ""
        ;;
esac
