#!/usr/bin/env bash
# smoke-md2confluence.sh  -  offline sanity checks for md2confluence-v3.py.
# Imports the module from its file path and exercises the pure conversion
# layer: front-matter parsing, the TR/EN punctuation gate (fancy punctuation
# stripped, diacritics preserved), and markdown -> storage-XML rendering for
# headings, tables, and code blocks. No network, no credentials, no Confluence.

set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
MOD="$REPO_ROOT/pipeline/lib/md2confluence-v3.py"

if ! command -v python3 >/dev/null 2>&1; then
  echo "smoke-md2confluence: python3 not found; skipping" >&2
  exit 0
fi

if [ ! -f "$MOD" ]; then
  echo "  ✗ md2confluence-v3.py missing at $MOD" >&2
  exit 1
fi

MOD_PATH="$MOD" python3 - <<'PYEOF'
import importlib.util
import os
import sys

spec = importlib.util.spec_from_file_location("md2c", os.environ["MOD_PATH"])
mod = importlib.util.module_from_spec(spec)
sys.modules["md2c"] = mod  # dataclass introspection needs the module registered
spec.loader.exec_module(mod)

passed = 0
failed = 0

def ok(msg):
    global passed
    print(f"  ✓ {msg}")
    passed += 1

def fail(msg):
    global failed
    print(f"  ✗ {msg}", file=sys.stderr)
    failed += 1

# --- parse_front_matter ------------------------------------------------------
print("→ parse_front_matter")
fm, body = mod.parse_front_matter("---\nfeature: Sample\nlanguage: tr\n---\n# Heading\nbody text\n")
if fm.get("feature") == "Sample" and fm.get("language") == "tr":
    ok("front-matter keys parsed")
else:
    fail(f"front-matter parse wrong: {fm}")
if body.startswith("# Heading"):
    ok("body separated from front-matter")
else:
    fail(f"body not separated: {body[:40]!r}")

fm2, body2 = mod.parse_front_matter("# No front matter\n")
if fm2 == {} and body2.startswith("# No"):
    ok("no-front-matter input passes through")
else:
    fail("no-front-matter input mangled")

# --- apply_punctuation_gate ----------------------------------------------------
print("→ apply_punctuation_gate")
dirty = "Geliştirme Özeti — kullanıcı için “detay” …"
clean, warnings = mod.apply_punctuation_gate(dirty, "tr")
forbidden = ["—", "–", "…", "“", "”", "‘", "’"]
if not any(ch in clean for ch in forbidden):
    ok("fancy punctuation stripped")
else:
    fail(f"fancy punctuation survived: {clean!r}")
for ch in ("ş", "Ö", "ı", "ç"):
    if ch not in clean:
        fail(f"diacritic {ch!r} was lost - gate must not ASCII-fold")
        break
else:
    ok("Turkish diacritics preserved")

# --- markdown_to_storage ---------------------------------------------------------
print("→ markdown_to_storage")
md = "\n".join([
    "# Title",
    "",
    "Intro paragraph.",
    "",
    "| A | B |",
    "|---|---|",
    "| 1 | 2 |",
    "",
    "```swift",
    "let x = 1",
    "```",
])
res = mod.markdown_to_storage(
    md,
    attachments_available=set(),
    mermaid_fallback=True,
    tooltip_macro_supported=False,
)
xml = res.storage_xml
checks = [
    ("<h1>", "h1 heading rendered"),
    ("<table>", "table rendered"),
    ("ac:structured-macro", "code block rendered as macro"),
]
for needle, label in checks:
    if needle in xml:
        ok(label)
    else:
        fail(f"{label}: {needle!r} not found in storage XML")

if res.images_referenced == []:
    ok("no phantom image references")
else:
    fail(f"unexpected images referenced: {res.images_referenced}")

# --- summary -------------------------------------------------------------------
print()
if failed == 0:
    print(f"══ md2confluence smoke: {passed} passed, 0 failed ══")
    sys.exit(0)
print(f"══ md2confluence smoke: {passed} passed, {failed} failed ══", file=sys.stderr)
sys.exit(1)
PYEOF
