"""
Extract release notes for the given tag
"""

from __future__ import absolute_import, unicode_literals

import argparse
import io
import logging
import os
import re
import sys

logger = logging.getLogger(__name__)

PSEUDO_MESSAGE = """\
This is a pseudo-release used only to stage artifacts for the release pipeline.
Please do not rely on the artifacts contained in this release as they change
frequently and are very likely to be broken.
""".replace("\n", " ")

GENERIC_MESSAGE = """
This release was automatically generated by the release pipeline.
""".strip()


def iterate_until_version(infile, version):
  history = []
  ruler = re.compile("^-+$")

  for line in infile:
    line = line.rstrip()
    history.append(line)

    if len(history) < 3:
      continue

    if (ruler.match(history[-3]) and
        version.match(history[-2]) and
        ruler.match(history[-1])):
      return

    if len(history) > 3:
      for buffered_line in history[:-3]:
        yield buffered_line
      history = history[-3:]

  for buffered_line in history:
    yield buffered_line


def get_note_text(infile_path, tag):
  if tag.startswith("pseudo-"):
    return PSEUDO_MESSAGE

  version_regex = re.compile(r"^(v\d+\.\d+\.\d+).*")
  match = version_regex.match(tag)
  if not match:
    return GENERIC_MESSAGE

  version_str = match.group(1)
  with io.open(infile_path, "r", encoding="utf-8") as infile:
    for _ in iterate_until_version(infile, re.compile(version_str)):
      pass

    content = "\n".join(iterate_until_version(infile, version_regex))
    return re.sub(r"(\S)\n(\S)", r"\1\2", content).strip()


def main():
  parser = argparse.ArgumentParser(description=__doc__)
  parser.add_argument("infile_path")
  parser.add_argument("tag")
  parser.add_argument("-o", "--outfile-path", default="-")

  args = parser.parse_args()

  if args.outfile_path == "-":
    args.outfile_path = os.dup(sys.stdout.fileno())
  with io.open(args.outfile_path, "w", encoding="utf-8") as outfile:
    outfile.write(get_note_text(args.infile_path, args.tag))
    outfile.write("\n")


if __name__ == "__main__":
  main()
