import std/[strutils, unittest]

import ../src/kjv
import ../src/reference_parser

suite "reference parser":
  test "parses single verse references":
    let reference = parseReference("John 3:16")

    check reference.book.code == "JHN"
    check reference.ranges.len == 1
    check reference.ranges[0].start.chapter == 3
    check reference.ranges[0].start.verse == 16
    check reference.ranges[0].finish == reference.ranges[0].start
    check $reference == "John 3:16"

  test "parses verse lists using the previous chapter":
    let reference = parseReference("John 3:16,20-21")

    check reference.ranges.len == 2
    check reference.ranges[1].start.chapter == 3
    check reference.ranges[1].start.verse == 20
    check reference.ranges[1].finish.chapter == 3
    check reference.ranges[1].finish.verse == 21
    check $reference == "John 3:16, 3:20-21"

  test "parses chapter ranges":
    let reference = parseReference("John 3-4")

    check reference.ranges.len == 1
    check reference.ranges[0].start.chapter == 3
    check reference.ranges[0].start.verse == 0
    check reference.ranges[0].finish.chapter == 4
    check reference.ranges[0].finish.verse == 0
    check $reference == "John 3-4"

  test "parses abbreviated numbered books":
    let reference = parseReference("1 Jn 1:9")

    check reference.book.code == "1JN"
    check reference.ranges[0].start.chapter == 1
    check reference.ranges[0].start.verse == 9
    check $reference == "1 John 1:9"

  test "parses unique canonical book prefixes":
    check parseReference("Gene 1:1").book.code == "GEN"
    check parseReference("Phile 3").book.code == "PHM"
    check parseReference("Phili 1:6").book.code == "PHP"

  test "rejects ambiguous canonical book prefixes":
    expect ValueError:
      discard parseReference("Phil 1")

  test "normalizes single-chapter book references":
    let reference = parseReference("Jude 3-4")

    check reference.book.code == "JUD"
    check reference.ranges[0].start.chapter == 1
    check reference.ranges[0].start.verse == 3
    check reference.ranges[0].finish.chapter == 1
    check reference.ranges[0].finish.verse == 4
    check $reference == "Jude 3-4"

  test "parses semicolon-separated references":
    let references = parseReferences("Psalm 23; John 3:16")

    check references.len == 2
    check references[0].book.code == "PSA"
    check references[1].book.code == "JHN"

suite "offline KJV backend":
  test "fetches a single embedded verse":
    let passages = kjv.fetchPassages("John 3:16")

    check passages.len == 1
    check passages[0].startsWith("John 3:16\n")
    check passages[0].contains("  [16] ")

  test "fetches a single-chapter embedded verse":
    let passages = kjv.fetchPassages("Jude 3")

    check passages.len == 1
    check passages[0].startsWith("Jude 3\n")
    check passages[0].contains("  [3] ")
