from io import StringIO
from pathlib import Path

from pandas import DataFrame

try:
    from src.model import validity  # for quarto document scripts
except ModuleNotFoundError:
    from model import validity  # for directly running the package


def extract(df: DataFrame, file: Path | StringIO) -> None:
    (
        validity.calculate(df)
        .drop(labels=["observation"], axis="columns")
        .to_csv(file, index=False, encoding="utf-8")
    )


if __name__ == "__main__":
    import os
    import sys

    import load_data

    if len(sys.argv) == 2:
        df = load_data.from_yml(Path(sys.argv[1]))
    else:
        df = load_data.from_yml()

    output = StringIO()
    extract(df, output)
    output.seek(0)
    try:
        print(output.read())
    except BrokenPipeError:
        devnull = os.open(os.devnull, os.O_WRONLY)
        os.dup2(devnull, sys.stdout.fileno())
