"""Example: extract structured entities from a crime report.

Prerequisites:
    - Ollama running locally (``ollama serve``).
    - The qwen2.5:7b-instruct model pulled (``ollama pull qwen2.5:7b-instruct``).
    - llm-ner installed in the active environment (``uv sync``).

Run::

    python -m examples.crime_extraction.run
    # or directly:
    python examples/crime_extraction/run.py
"""

from __future__ import annotations

import sys
from pathlib import Path

# When running this script directly (not as a module), ensure the project root
# is on sys.path so that ``examples`` can be imported as a package.
if __name__ == "__main__":
    _PROJECT_ROOT = str(Path(__file__).resolve().parents[2])
    if _PROJECT_ROOT not in sys.path:
        sys.path.insert(0, _PROJECT_ROOT)

from examples.crime_extraction.schema import CrimeReport, create_extractor

# ---------------------------------------------------------------------------
# Sample report (English translation of a Spanish police complaint)
# ---------------------------------------------------------------------------

SAMPLE_REPORT = """
On 15 March 2024 at 14:30, the complainant was walking along Oak Street 12
when he was approached from behind by two individuals. The first suspect, a
male of Romanian appearance, approximately 28-32 years old, around 180 cm
tall, with brown hair, threatened him verbally and demanded his mobile phone.
The second suspect, a male of North African appearance, approximately 25-27
years old, around 170-175 cm tall, with dark hair, grabbed the complainant
by the arm using physical force while the first suspect snatched the phone.
Both suspects fled on foot towards the city centre.
"""


def main() -> None:
    extractor = create_extractor()

    print("Extracting entities from report...")
    result: CrimeReport | None = extractor.extract_one(SAMPLE_REPORT)  # type: ignore[assignment]

    if result is None:
        print("Extraction failed – check that Ollama is running.")
        return

    # ── Facts ─────────────────────────────────────────────────────────────
    if result.facts:
        print("\n=== FACTS ===")
        if result.facts.datetime:
            print(f"  Datetime : {result.facts.datetime.value!r}")
            print(f"  Evidence : {result.facts.datetime.evidence!r}")
        if result.facts.address:
            print(f"  Address  : {result.facts.address.value!r}")
            print(f"  Evidence : {result.facts.address.evidence!r}")

    # ── Modus operandi ────────────────────────────────────────────────────
    if result.modus_operandi and result.modus_operandi.weapon_method:
        print("\n=== MODUS OPERANDI ===")
        print(f"  Method   : {result.modus_operandi.weapon_method.value!r}")
        print(f"  Evidence : {result.modus_operandi.weapon_method.evidence!r}")

    # ── Suspects ──────────────────────────────────────────────────────────
    print(f"\n=== SUSPECTS ({len(result.suspects)} found) ===")
    for i, suspect in enumerate(result.suspects, 1):
        print(f"\n  Suspect #{i}: {suspect.summary()}")
        row = suspect.model_dump(by_alias=True)
        for field, value in row.items():
            if isinstance(value, dict):
                print(
                    f"    {field:15s}: {value.get('value')!r:20}  ev={value.get('evidence')!r}"
                )


if __name__ == "__main__":
    main()
