#!/usr/bin/env python
# Exercise 7
# grep command

import re
import sys
import argparse
from pathlib import Path


def loop(args):
    stderr = False
    for path in args["paths"]:
        if not path.exists():
            print(f"grep: {path}: No existe el fichero o el directorio")
            stderr = True
        elif path.is_dir():
            print(f"grep: {path}: Es un directorio")
            stderr = True
        else:
            grep(path, args)
    return stderr


def grep(path, args):
    lines = open(path, "r").readlines()
    res = []
    pre = ""
    if len(args["paths"]) > 1:
        pre = f"{path}:"
    for line in lines:
        tmp = line[:]
        if args["ignore_case"]:
            tmp = tmp.lower()
        if args["extended_regexp"]:
            res = re.compile(args["extended_regexp"]).search(tmp)
        else:
            res = tmp.find(args["query"])
        if res is not None and res != -1:
            print(f"{pre}{line}", end="")


parser = argparse.ArgumentParser()
parser.add_argument("paths", nargs="+", type=Path)
parser.add_argument("-i", "--ignore-case", default=False, action="store_true")
parser.add_argument("-E", "--extended-regexp", default=False, type=str)

if len(sys.argv) > 1:
    if sys.argv[1] != "-E" and sys.argv[1] != "-i":
        query = str(sys.argv[1])
        del sys.argv[1]
    else:
        query = False
    args = parser.parse_args().__dict__
    args["query"] = query
    stderr = loop(args)
    if stderr:
        sys.exit(1)
else:
    sys.exit(1)
