"""A local CSV-to-Markdown exercise. Preview by default; --write saves the result."""
import argparse
import csv
import os
import sys
import tempfile
from pathlib import Path


def make_brief(source):
    with Path(source).open(newline="", encoding="utf-8-sig") as stream:
        reader = csv.DictReader(stream, strict=True)
        headers = reader.fieldnames or []
        if len(headers) != len(set(headers)):
            raise ValueError("Column names must be unique.")
        if not {"task", "owner", "status"}.issubset(headers):
            raise ValueError("CSV must contain task, owner and status columns.")
        tasks = []
        for row in reader:
            if None in row or any(value is None for value in row.values()):
                raise ValueError(f"CSV line {reader.line_num}: column count does not match the header.")
            task, owner, status = (row[key].strip() for key in ("task", "owner", "status"))
            if not task:
                raise ValueError(f"CSV line {reader.line_num}: a task name is required.")
            if any(c in task + owner for c in "\r\n"):
                raise ValueError(f"CSV line {reader.line_num}: task and owner must each fit on one line.")
            if status.lower() not in {"open", "done"}:
                raise ValueError(f"CSV line {reader.line_num}: status must be open or done.")
            if status.lower() == "open":
                tasks.append(f"- {task} — {owner or 'Unassigned'}")
    return f"# Project brief\n\nOpen tasks: {len(tasks)}\n\n" + "\n".join(tasks) + "\n"


def write_brief(destination, text):
    destination = Path(destination)
    temporary = None
    try:
        with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n",
                                         dir=destination.parent, prefix=".brief-", delete=False) as stream:
            temporary = Path(stream.name)
            stream.write(text)
        os.replace(temporary, destination)
    finally:
        if temporary is not None and temporary.exists():
            temporary.unlink()


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source", type=Path)
    parser.add_argument("destination", type=Path)
    parser.add_argument("--write", action="store_true", help="Replace the destination with the validated brief.")
    args = parser.parse_args(argv)
    try:
        if args.source.resolve() == args.destination.resolve():
            raise ValueError("Choose an output path different from the input.")
        result = make_brief(args.source)
        if args.write:
            write_brief(args.destination, result)
            print(f"Wrote {args.destination}")
        else:
            print("PREVIEW ONLY — no file written. Add --write to save.\n")
            print(result, end="")
        return 0
    except (OSError, ValueError, csv.Error, UnicodeError) as error:
        print(f"Could not create brief: {error}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
