#!/bin/bash
# 删除 SDK 包，同步清理 workspace、IDE 模块注册、各包依赖引用
#
# 用法：
#   melos run remove:sdk -- push        # 删除 packages/push_sdk/
#   melos run remove:sdk -- push_sdk    # 同上

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

if [[ $# -eq 0 ]]; then
  echo "Usage: melos run remove:sdk -- <name>"
  echo "Example: melos run remove:sdk -- push"
  exit 1
fi

INPUT="$1"
BASE_NAME="${INPUT%_sdk}"
PKG_NAME="${BASE_NAME}_sdk"
PKG_DIR="$ROOT_DIR/packages/$PKG_NAME"

if [[ ! -d "$PKG_DIR" ]]; then
  echo "Warning: packages/$PKG_NAME not found. Will still clean up config references."
  read -r -p "Continue cleanup? [y/N] " REPLY
else
  echo "About to permanently delete packages/$PKG_NAME and clean up all references."
  read -r -p "Confirm? [y/N] " REPLY
fi
if [[ ! "$REPLY" =~ ^[Yy]$ ]]; then
  echo "Aborted."
  exit 0
fi

# ---- 删除包目录 ----
if [[ -d "$PKG_DIR" ]]; then
  rm -rf "$PKG_DIR"
  echo "Removed packages/$PKG_NAME"
else
  echo "Skipped directory removal (already gone)"
fi

# ---- 更新根 pubspec.yaml workspace ----
python3 - "$ROOT_DIR/pubspec.yaml" "$PKG_NAME" << 'PY'
import sys

pubspec_path, pkg_name = sys.argv[1], sys.argv[2]
with open(pubspec_path) as f:
    lines = f.readlines()

entry = f'  - packages/{pkg_name}\n'
lines = [l for l in lines if l != entry]

with open(pubspec_path, 'w') as f:
    f.writelines(lines)
PY
echo "Updated pubspec.yaml workspace"

# ---- 更新 .idea/modules.xml ----
python3 - "$ROOT_DIR/.idea/modules.xml" "$PKG_NAME" << 'PY'
import sys, re

modules_path, pkg_name = sys.argv[1], sys.argv[2]
with open(modules_path) as f:
    content = f.read()

pattern = rf'[ \t]*<module[^>]*packages/{re.escape(pkg_name)}/[^>]*/>\n'
content = re.sub(pattern, '', content)

with open(modules_path, 'w') as f:
    f.write(content)
PY
echo "Updated .idea/modules.xml"

# ---- 扫描并移除其他包中的依赖引用 ----
python3 - "$ROOT_DIR" "$PKG_NAME" << 'PY'
import sys, os, re, glob

root_dir, pkg_name = sys.argv[1], sys.argv[2]

pubspecs = glob.glob(os.path.join(root_dir, 'apps', '*', 'pubspec.yaml')) + \
           glob.glob(os.path.join(root_dir, 'packages', '*', 'pubspec.yaml'))

pattern = re.compile(rf'^\s+{re.escape(pkg_name)}\s*:.*\n', re.MULTILINE)

for path in pubspecs:
    with open(path) as f:
        content = f.read()
    updated = pattern.sub('', content)
    if updated != content:
        with open(path, 'w') as f:
            f.write(updated)
        rel = os.path.relpath(path, root_dir)
        print(f'  Removed {pkg_name} from {rel}')
PY
echo "Scanned dependency references"

# ---- dart pub get ----
echo ""
cd "$ROOT_DIR" && dart pub get

echo ""
echo "Done. packages/$PKG_NAME removed."
