#!/usr/bin/env python
# Exercise 9
# sed command

import re
import sys
import argparse
from pathlib import Path


def check(expression, exp):
    error = False
    if (
        expression[-1] not in "/g"
        or exp[0] not in "s"
        or len(exp) not in range(3, 5)
        or (expression[-1] in "g" and len(exp) != 4)
        or (expression[-1] in "/" and len(exp) == 4)
    ):
        error = True
    if error:
        print(f"sed: expresión «{expression}» inválida")
        sys.exit(1)


def parse(expression):
    count = 0
    exp = list(filter(None, expression.split("/")))
    check(expression, exp)
    if len(exp) == 3:
        count = 1
    return {
        "rgx": re.compile(exp[1]),
        "rep": exp[2],
        "n": count,
    }


parser = argparse.ArgumentParser()
parser.add_argument("stream", default=sys.stdin, nargs="*")
parser.add_argument(
    "-e", "--expression", required=True, type=str, action="append"
)
args = parser.parse_args()
res = ""

for exp in args.expression:
    exp = parse(exp)
    for stream in args.stream:
        if isinstance(args.stream, list):
            stream = Path(stream).read_text()
        else:
            stream = stream.strip()
        if res == "":
            res = stream
        res = re.sub(exp["rgx"], exp["rep"], res, count=exp["n"])
print(res)
