"""CLI shim — ks-xlsx-parser -> Markdown with form-layout consolidation.

All pipeline logic lives in ``src.extraction_v2.ks_parser``.
This script handles argument parsing + output filename behavior only.

Outputs in CWD:
    <base>.ks_fix.md
"""
from __future__ import annotations

import argparse
import logging
import os
import shutil
import sys
import tempfile
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT))

from src.extraction_v2.ks_parser import ksparser_to_md, ksparser_to_sheets
from src.extraction_v2.ks_parser.mermaid import (
    collect_mermaid_blocks,
    convert_xls_to_xlsx,
    restore_mermaid_blocks,
)
from src.extraction_v2.ks_parser.pipeline import (
    _lift_sentinels_from_tables,
    _strip_orphan_separator_tables,
)
from src.extraction_v2.xlsx_header_injection import convert_sentinels_to_atx

logger = logging.getLogger("inject_headers_and_parse_ks_fix")


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("xlsx", help="Input .xls/.xlsx/.xlsm")
    ap.add_argument("--converter", default="ks", help="Converter to use (kept for CLI compat; only 'ks' is supported)")
    ap.add_argument("-v", "--verbose", action="store_true")
    args = ap.parse_args()
    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format="%(asctime)s %(levelname)s %(name)s: %(message)s",
    )

    src = args.xlsx
    if not os.path.exists(src):
        logger.error("input not found: %s", src)
        return 2

    xls_tmp_dir: str | None = None
    if src.lower().endswith(".xls"):
        xls_tmp_dir = tempfile.mkdtemp(prefix="xls2xlsx_")
        logger.info("converting legacy .xls -> .xlsx via LibreOffice")
        src = convert_xls_to_xlsx(src, xls_tmp_dir)
        logger.info("converted: %s", src)
    elif not src.lower().endswith((".xlsx", ".xlsm")):
        logger.error("input must be .xls/.xlsx/.xlsm")
        return 2

    base_name = Path(src).stem
    if base_name.endswith(".preprocessed"):
        base_name = base_name[: -len(".preprocessed")]

    out_md = os.path.join(os.getcwd(), f"{base_name}.ks_fix.md")

    mermaid_blocks = collect_mermaid_blocks(src)
    logger.info("found %d mermaid block(s) embedded in xlsx", len(mermaid_blocks))

    md_raw = ksparser_to_md(src)
    md, n_restored = restore_mermaid_blocks(md_raw, mermaid_blocks)
    logger.info("restored mermaid newlines for %d/%d block(s)", n_restored, len(mermaid_blocks))
    md, n_lifted = _lift_sentinels_from_tables(md)
    if n_lifted:
        logger.info("lifted %d sentinel(s) out of table rows", n_lifted)
    md, hdr_counts = convert_sentinels_to_atx(md)
    if hdr_counts:
        logger.info("materialized headers: %s", hdr_counts)
    md, n_orphans = _strip_orphan_separator_tables(md)
    if n_orphans:
        logger.info("stripped %d orphan separator-only table(s)", n_orphans)

    with open(out_md, "w", encoding="utf-8") as fh:
        fh.write(md)
    logger.info("wrote %s (%d chars)", out_md, len(md))

    if xls_tmp_dir:
        shutil.rmtree(xls_tmp_dir, ignore_errors=True)

    print()
    print(f"Markdown: {out_md}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
