#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Web example script to get HTML author URL from author in list
# Copyright (C) 2014-2026 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: thomas.dreibholz@gmail.com
#

import csv
import re
import sys

if sys.version_info < (3, 9):
   sys.stderr.write('ERROR: ' + sys.argv[0] + ' requires Python 3.9 or later!\n')
   sys.exit(1)

from typing import Final, TextIO


# ###### Main program #######################################################
if len(sys.argv) != 4:
   sys.stderr.write('Usage: ' + sys.argv[0] + ' author_list author_name default_text\n')
   sys.exit(1)

replaceBbspStrings : Final[re.Pattern[str]] = re.compile(r'&nbsp;', re.UNICODE)

authorList : Final[str] = sys.argv[1]
authorName : Final[str] = replaceBbspStrings.sub(' ', sys.argv[2])
authorText : Final[str] = sys.argv[3]


csv.register_dialect('authors', delimiter=' ', quoting=csv.QUOTE_MINIMAL,skipinitialspace=True)

inputFile : TextIO = open(authorList, 'r')
inputCSV = csv.reader(inputFile, dialect='authors')

authorRow : list[str] | None = None
for row in inputCSV:
   # print(row)
   if row[0] == authorName:
      if authorRow is not None:
         # the authorName is multiple times in the table -> warning
         sys.stderr.write('WARNING: Multiple occurrences of authorName ' + authorName + ' in ' + authorList + '!\n')
      authorRow = row


if authorRow is None:
   # The authorName is not in the table -> use default text
   sys.stdout.write(authorText)
   sys.stderr.write('Not in list: ' + authorName + '\n')
   sys.exit(0)
else:
   # Found the authorName -> print the result
   sys.stdout.write('<a href="' + authorRow[1] + '">' + authorText + '</a>')
