#!/usr/bin/env python3
"""Run ExcelParserService.parse_to_markdown on an xlsx/xlsm file and write per-sheet markdown.

Usage:
    uv run python scripts/run_excel_parser_service.py <path/to/file.xlsx> [--out output.md]

Output file defaults to <basename>.service.md in CWD.
"""
from __future__ import annotations

import argparse
import asyncio
import os
import sys
import uuid
from pathlib import Path

# Make src importable without sys.path hacks
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import structlog
import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
log = structlog.get_logger("run_excel_parser_service")


async def main(xlsx_path: str, out_path: str) -> None:
    from src.extraction_v2.excel_parser_service import get_excel_parser_service

    service = get_excel_parser_service()
    file_id = uuid.uuid4()
    filename = Path(xlsx_path).name

    log.info("reading file", path=xlsx_path)
    with open(xlsx_path, "rb") as f:
        content = f.read()

    log.info("calling parse_to_markdown", file_id=str(file_id), filename=filename)
    result = await service.parse_to_markdown(
        file_content=content,
        file_id=file_id,
        original_filename=filename,
    )

    sheets = result.get("sheets", [])
    image_chunks = result.get("image_chunks", [])
    flowchart_chunks = result.get("flowchart_chunks", [])

    log.info(
        "parse complete",
        sheets=len(sheets),
        image_chunks=len(image_chunks),
        flowchart_chunks=len(flowchart_chunks),
    )

    parts: list[str] = []
    for sheet in sheets:
        name = sheet["sheet_name"]
        md = sheet["markdown"]
        parts.append(f"<!-- === SHEET: {name} === -->\n\n{md}")
        log.info("sheet", name=name, chars=len(md))

    combined = "\n\n---\n\n".join(parts)

    with open(out_path, "w", encoding="utf-8") as f:
        f.write(combined)

    print(f"\nWrote {len(sheets)} sheet(s) → {out_path} ({len(combined):,} chars)")
    if image_chunks:
        print(f"Image chunks: {len(image_chunks)} (not written to md)")


def parse_args() -> argparse.Namespace:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("xlsx", help="Input .xlsx / .xlsm / .xls file")
    ap.add_argument("--out", default=None, help="Output .md path (default: <basename>.service.md)")
    return ap.parse_args()


if __name__ == "__main__":
    args = parse_args()

    if not os.path.exists(args.xlsx):
        print(f"ERROR: file not found: {args.xlsx}", file=sys.stderr)
        sys.exit(1)

    out = args.out or os.path.join(
        os.getcwd(), Path(args.xlsx).stem + ".service.md"
    )

    asyncio.run(main(args.xlsx, out))
