import csv
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
RAW_PATH = os.path.join(BASE_DIR, "raw.txt")
OUT_PATH = os.path.join(BASE_DIR, "data", "narrative.csv")

NARRATIVE_MARKERS = [
    "then", "after", "before", "when",
    "suddenly", "eventually", "once",
    "later", "earlier", "while"
]

EXPLANATORY_MARKERS = [
    "explains", "describes", "refers to",
    "defined as", "consists of",
    "is used to", "means that"
]


def load_raw_text(path):
    with open(path, "r", encoding="utf-8") as f:
        return [line.strip() for line in f if line.strip()]


def label_text(text):
    t = text.lower()

    for m in NARRATIVE_MARKERS:
        if m in t:
            return 1

    for m in EXPLANATORY_MARKERS:
        if m in t:
            return 0

    # default to explanatory (safer)
    return 0


def main():
    texts = load_raw_text(RAW_PATH)

    with open(OUT_PATH, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["text", "label"])

        for text in texts:
            writer.writerow([text, label_text(text)])

    print(f"Narrative dataset written to {OUT_PATH}")


if __name__ == "__main__":
    main()
