""" Top-level processing logic for doc_file_processing """

from __future__ import annotations

import json
from pathlib import Path
from typing import Generator, List

from configuration import process_doc
from export import export
from logutil import *
from reader_doc import DOCReader
from reader_docx import DOCXReader
from winutil import make_valid_filename


FAILURES: List[Path] = []


def search_directory(input_dir_path: Path) -> Generator[Path, None, None]:
    """ Find all exportable documents in a directory. """
    for input_path in input_dir_path.iterdir():
        if input_path.is_dir():
            yield from search_directory(input_path)
        elif input_path.suffix in ('.doc', '.docx'):
            yield input_path

def process_files(input_paths: list[Path], output_dir_path: Path) -> None:
    """ Export configuration from multiple documents. """
    file_ct = len(input_paths)
    for i, input_path in enumerate(input_paths):
        progress_major(i, file_ct)
        statusmsg(f'Processing {input_path} ({i+1}/{file_ct})', progress_major=True, progress_compact=True)
        try:
            process_file(input_path, output_dir_path)
        except Exception:
            errmsg(f"** Failed to export document {input_path} **")
            errexc()
            FAILURES.append(input_path)

def process_file(input_file_path: Path, output_dir_path: Path) -> None:
    """ Export configuration from a single document. """
    output_path = output_dir_path / make_valid_filename(input_file_path.stem)

    progress_minor(0, 4)

    # Read document
    statusmsg("  Reading document...")
    ext = input_file_path.suffix.lower()
    if ext == '.doc':
        doc = DOCReader(input_file_path)
    elif ext == '.docx':
        doc = DOCXReader(input_file_path)
    else:
        raise RuntimeError(f"Cannot determine input format for {input_file_path} -- unknown file extension {ext}")
    progress_minor(1, 4)

    # Check if configuration
    if not doc.is_config():
        wrnmsg(f"  Not an AC 800M export document: {input_file_path} -- skipping file")
        return

    # Parse document into content
    statusmsg(f'  Processing document...')
    content = doc.parse()
    progress_minor(2, 4)

    # Parse content into configuration
    timestamp = doc.timestamp()
    config = process_doc(content, input_file_path.stem, input_file_path, timestamp)
    progress_minor(3, 4)

    # Export configuration
    statusmsg(f'  Exporting configuration...')
    output_path.mkdir(parents=True, exist_ok=True)

    data = export(config, output_path, doc)
    data_path = output_path / 'data.json'
    with open(data_path, 'w') as data_file:
        json.dump(data, data_file)
    progress_minor(4, 4)


def get_failures() -> List[Path]:
    """ List all documents which failed to export. """
    return FAILURES