"""Read decisions/outcomes.csv, the one record of decision outcomes. It is edited by hand.

It has one row per decision that belongs to a theme in definitions/decisions_def.py (DEC-...) and one per row
of definitions/tech_stack.csv (TS-01 to TS-32):

  id                decision ID, or TS-<row> for a technology stack row
  item              short label of the decision or technology item
  status            Open, Under evaluation, Proposed, Decided or Deferred
  settled           yes: chosen_option is the outcome and the specification records the decision as Resolved
                    no:  chosen_option only says how or when the decision will be made; it stays Open
  chosen_option     the outcome (settled) or the agreed approach (not settled). For a decision whose outcome
                    is the technology chosen on technology stack rows, the text "See the Tech stack sheet"
  proposed_outcome  a draft outcome under review, not yet decided
  decided_by, date_decided (YYYY-MM-DD), adr_reference, notes
  recorded          date the chosen option was entered here; used when date_decided is empty
"""
import csv, datetime, os

HERE = os.path.dirname(os.path.abspath(__file__))
PLAN = os.path.dirname(HERE)
CSV = os.path.join(PLAN, 'decisions', 'outcomes.csv')
TECH_STACK = os.path.join(HERE, 'definitions', 'tech_stack.csv')
FIELDS = ['id', 'item', 'status', 'settled', 'chosen_option', 'proposed_outcome', 'decided_by', 'date_decided',
          'adr_reference', 'recorded', 'notes']
STATUSES = ['Open', 'Under evaluation', 'Proposed', 'Decided', 'Deferred']
FROM_TECH = 'See the Tech stack sheet'


def norm(v):
    """CSV value to a comparable string."""
    if v is None:
        return ''
    if isinstance(v, (datetime.datetime, datetime.date)):
        return v.strftime('%Y-%m-%d')
    return str(v).replace('\r\n', '\n').strip()


def tech_id(no):
    return f'TS-{int(no):02d}'


def read():
    rows = {}
    with open(CSV, newline='') as fh:
        for r in csv.DictReader(fh):
            r = {k: norm(r.get(k)) for k in FIELDS}
            if r['id'] in rows:
                raise SystemExit(f'outcomes.csv: {r["id"]} appears twice')
            if r['status'] not in STATUSES:
                raise SystemExit(f'outcomes.csv: {r["id"]} has status "{r["status"]}"; use one of {", ".join(STATUSES)}')
            if r['settled'] not in ('yes', 'no'):
                raise SystemExit(f'outcomes.csv: {r["id"]} has settled "{r["settled"]}"; use yes or no')
            if r['status'] == 'Decided' and r['settled'] != 'yes':
                raise SystemExit(f'outcomes.csv: {r["id"]} has status Decided but settled is not yes')
            rows[r['id']] = r
    return rows


def read_tech_stack():
    with open(TECH_STACK, newline='') as fh:
        return list(csv.DictReader(fh))
