#!/usr/bin/env python3
"""
JoySpace Sheet Split Pipeline
按指定列分拆源工作表数据到多个目标工作表，可选配置保护范围。

改编自 joyspace-sheet-ops 的 split_sheet_by_column，
改用 JoySpaceClient 替代 color_request/cookie 认证。

功能：
  - 按筛选列值自动分拆源表数据到目标工作表
  - 自动检测目标工作表（精确匹配 → 子串匹配）
  - 写入前自动清空目标区域（可关闭）
  - 清空失败自动回退为写空格
  - 分页读取，分批写入
  - 写入后可验证
  - 支持 dry-run
"""
from __future__ import annotations

from _monitor_autoload import finbox_autoload
finbox_autoload()

import argparse
import json
import sys
from pathlib import Path
from typing import Any

# 本地 api/auth/utils 已内置，直接 import
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from api.gateway import JoySpaceClient  # noqa: E402
from api import sheets as sheets_api  # noqa: E402
from utils.url_parser import parse_page_url  # noqa: E402

READ_CHUNK_SIZE = 500
MAX_WRITE_ITEMS = 500


def _log(stage: str, message: str) -> None:
    print(f"[sheet-split] {stage}: {message}", file=sys.stderr, flush=True)


# ─── 工作表元信息 ───

def get_all_worksheets(client: JoySpaceClient, page_id: str) -> list[dict[str, Any]]:
    result = sheets_api.get_et_worksheets(client, {"page_id": page_id})
    ws_list = result.get("data", {}).get("sheets", [])
    for s in ws_list:
        area = s.get("activeArea") or {}
        s["activeRowTo"] = area.get("rowTo", 0)
        s["activeColTo"] = area.get("colTo", 0)
    return ws_list


def find_sheet_by_name(ws_list: list[dict[str, Any]], name: str) -> dict[str, Any]:
    for s in ws_list:
        if s.get("name") == name:
            return s
    available = [s.get("name", f"(id={s.get('sheetId')})") for s in ws_list]
    raise ValueError(f"Worksheet '{name}' not found. Available: {', '.join(available)}")


# ─── 读取数据 ───

def read_range_as_table(
    client: JoySpaceClient, page_id: str, worksheet_id: int | str,
    row_from: int, row_to: int, col_from: int, col_to: int,
) -> list[list[str]]:
    result = sheets_api.get_et_range_data(client, {
        "page_id": page_id,
        "worksheet_id": str(worksheet_id),
        "row_from": row_from,
        "row_to": row_to,
        "col_from": col_from,
        "col_to": col_to,
    })
    range_data = result.get("data", {}).get("rangeData", [])
    rows = row_to - row_from + 1
    cols = col_to - col_from + 1
    table: list[list[str]] = [[""] * cols for _ in range(rows)]
    for cell in range_data:
        r = cell.get("rowFrom", 0) - row_from
        c = cell.get("colFrom", 0) - col_from
        if 0 <= r < rows and 0 <= c < cols:
            table[r][c] = cell.get("cellText") or ""
    return table


def read_all_data_paginated(
    client: JoySpaceClient, page_id: str, worksheet_id: int | str,
    col_from: int, col_to: int, max_row: int,
) -> list[list[str]]:
    if max_row <= 0:
        return []
    all_rows: list[list[str]] = []
    row_from = 0
    while row_from <= max_row:
        row_to = min(row_from + READ_CHUNK_SIZE - 1, max_row)
        chunk = read_range_as_table(client, page_id, worksheet_id, row_from, row_to, col_from, col_to)
        all_rows.extend(chunk)
        row_from = row_to + 1
    return all_rows


# ─── 写入数据 ───

def build_write_range_data(
    table: list[list[str]], start_row: int, start_col: int,
    clear_empty: bool = False,
) -> list[dict[str, Any]]:
    operations: list[dict[str, Any]] = []
    for r_idx, row in enumerate(table):
        for c_idx, value in enumerate(row):
            if value is not None and value != "":
                operations.append({
                    "opType": "cell_operation_type_formula",
                    "rowFrom": start_row + r_idx,
                    "rowTo": start_row + r_idx,
                    "colFrom": start_col + c_idx,
                    "colTo": start_col + c_idx,
                    "formula": str(value),
                })
            elif clear_empty:
                operations.append({
                    "opType": "cell_operation_type_formula",
                    "rowFrom": start_row + r_idx,
                    "rowTo": start_row + r_idx,
                    "colFrom": start_col + c_idx,
                    "colTo": start_col + c_idx,
                    "formula": " ",
                })
    return operations


def write_range(
    client: JoySpaceClient, page_id: str, worksheet_id: int | str,
    table: list[list[str]], start_row: int, start_col: int,
    clear_empty: bool = False,
) -> dict[str, Any]:
    operations = build_write_range_data(table, start_row, start_col, clear_empty=clear_empty)
    if not operations:
        return {"status": "skipped", "reason": "no data to write"}
    # 分批写入
    all_results = []
    for batch_start in range(0, len(operations), MAX_WRITE_ITEMS):
        batch = operations[batch_start:batch_start + MAX_WRITE_ITEMS]
        result = sheets_api.update_et_range_data(client, {
            "page_id": page_id,
            "worksheet_id": str(worksheet_id),
            "rangeData": batch,
        })
        all_results.append(result)
    return {"success": True, "batches": len(all_results)}


def clear_range(
    client: JoySpaceClient, page_id: str, worksheet_id: int | str,
    row_from: int, row_to: int, col_from: int, col_to: int,
) -> dict[str, Any]:
    # 优先用 deleteEtRangeData
    try:
        return sheets_api.delete_et_range_data(client, {
            "page_id": page_id,
            "worksheet_id": str(worksheet_id),
            "rangeData": [{"colFrom": col_from, "colTo": col_to, "rowFrom": row_from, "rowTo": row_to}],
        })
    except Exception:
        # deleteEtRangeData 常常 E_FAIL，回退为写空格
        cols = col_to - col_from + 1
        empty_table = [[""] * cols for _ in range(row_from, row_to + 1)]
        return write_range(client, page_id, worksheet_id, empty_table, row_from, col_from, clear_empty=True)


# ─── 保护范围 ───

def set_protection(
    client: JoySpaceClient, page_id: str, worksheet_id: int | str,
    protection_data: dict,
) -> dict[str, Any]:
    infos = protection_data.get("sheetsProtectionInfos")
    if not infos:
        infos = [{"worksheetId": int(worksheet_id), **protection_data}]
    return sheets_api.create_et_protection_ranges(client, {
        "page_id": page_id,
        "worksheet_id": str(worksheet_id),
        "sheetsProtectionInfos": infos,
    })


# ─── 主流程 ───

def run(
    page_url: str,
    source_sheet: str,
    filter_column: str,
    columns: list[str],
    *,
    target_sheets: list[str] | None = None,
    header_row: int = 0,
    write_start_row: int = 0,
    write_start_col: int = 0,
    clear_before_write: bool = True,
    clear_col_to: int | None = None,
    dry_run: bool = False,
    verify: bool = True,
    protection_data: dict | None = None,
    sso_token: str | None = None,
) -> dict[str, Any]:
    client = JoySpaceClient(sso_token=sso_token)
    page_id = parse_page_url(page_url)

    # 确保 filter_column 在 columns 中
    if filter_column not in columns:
        columns.insert(0, filter_column)

    data_start_row = header_row + 1
    effective_clear_col_to = clear_col_to if clear_col_to is not None else (write_start_col + len(columns) - 1)

    # Step 1: 获取所有 worksheet 元信息
    _log("step 1/8", "fetching worksheet metadata")
    all_sheets = get_all_worksheets(client, page_id)

    # Step 2: 定位源 sheet
    source_meta = find_sheet_by_name(all_sheets, source_sheet)
    source_ws_id = source_meta["sheetId"]
    source_active_row_to = source_meta.get("activeRowTo", 0)
    source_active_col_to = source_meta.get("activeColTo", 0)

    # Step 3: 读取源 sheet 表头，建立列映射
    if source_active_row_to <= 0 or source_active_col_to <= 0:
        return {"status": "error", "error": f"Source sheet '{source_sheet}' appears empty"}

    _log("step 3/8", f"reading header row {header_row}")
    header_rows = read_range_as_table(client, page_id, source_ws_id, header_row, header_row, 0, source_active_col_to)
    header = header_rows[0] if header_rows else []
    col_map = {name.strip(): idx for idx, name in enumerate(header)}

    for col_name in columns:
        if col_name not in col_map:
            return {"status": "error", "error": f"Column '{col_name}' not found. Available: {list(col_map.keys())}"}

    # Step 4: 读取源 sheet 全部数据
    _log("step 4/8", f"reading all data (up to row {source_active_row_to})")
    source_data = read_all_data_paginated(client, page_id, source_ws_id, 0, source_active_col_to, source_active_row_to)
    source_data_rows = source_data[data_start_row:]
    _log("step 4/8", f"read {len(source_data_rows)} data rows")

    # Step 5: 自动检测目标 sheets
    target_names = list(target_sheets) if target_sheets else []
    if not target_names:
        filter_col_idx = col_map[filter_column]
        unique_values = set()
        for row in source_data_rows:
            if filter_col_idx < len(row) and row[filter_col_idx]:
                unique_values.add(row[filter_col_idx].strip())

        unmatched_values = set(unique_values)
        # Pass 1: exact match
        for s in all_sheets:
            sname = s.get("name", "")
            if sname == source_sheet:
                continue
            if sname in unique_values and sname not in target_names:
                target_names.append(sname)
                unmatched_values.discard(sname)
        # Pass 2: substring match
        for s in all_sheets:
            sname = s.get("name", "")
            if sname == source_sheet or sname in target_names:
                continue
            for uv in list(unmatched_values):
                if uv in sname or sname in uv:
                    target_names.append(sname)
                    unmatched_values.discard(uv)
                    break

        if not target_names:
            return {"status": "error", "error": f"No target sheets auto-detected for filter values: {unique_values}"}

    # 构建目标 sheet 元信息映射
    target_metas = []
    missing_targets = []
    for tname in target_names:
        try:
            tmeta = find_sheet_by_name(all_sheets, tname)
            target_metas.append(tmeta)
        except ValueError:
            missing_targets.append(tname)

    if missing_targets:
        _log("warning", f"target sheets not found, skipping: {missing_targets}")
    if not target_metas:
        return {"status": "error", "error": f"No valid target sheets found. Missing: {missing_targets}"}

    # Step 6: 按筛选列过滤数据
    filter_col_idx = col_map[filter_column]
    target_col_indices = [col_map[cn] for cn in columns]

    filtered_by_target: dict[str, list[list[str]]] = {tmeta["name"]: [] for tmeta in target_metas}

    for row in source_data_rows:
        if filter_col_idx >= len(row):
            continue
        cell_value = row[filter_col_idx].strip()
        if not cell_value:
            continue
        matched = None
        # Pass 1: exact match
        for tmeta in target_metas:
            if cell_value == tmeta["name"]:
                matched = tmeta
                break
        # Pass 2: substring fallback
        if matched is None:
            for tmeta in target_metas:
                tname = tmeta["name"]
                if cell_value in tname or tname in cell_value:
                    matched = tmeta
                    break
        if matched is not None:
            filtered_row = [row[idx] if idx < len(row) else "" for idx in target_col_indices]
            filtered_by_target[matched["name"]].append(filtered_row)

    matched_counts = {n: len(rows) for n, rows in filtered_by_target.items() if rows}
    _log("step 6/8", f"filtered {len(source_data_rows)} rows → {sum(matched_counts.values())} matched across {len(matched_counts)} targets")

    # Step 7: Dry-run 或实际执行
    results = []
    total_targets = len(target_metas)
    for idx, tmeta in enumerate(target_metas, 1):
        tname = tmeta["name"]
        tws_id = tmeta["sheetId"]
        tactive_row_to = tmeta.get("activeRowTo", 0)
        filtered_rows = filtered_by_target[tname]

        _log(f"step 7/8 [{idx}/{total_targets}]", f"processing {tname} ({len(filtered_rows)} rows)")

        entry: dict[str, Any] = {
            "targetSheet": tname,
            "worksheetId": tws_id,
            "rowsToWrite": len(filtered_rows),
            "columns": columns,
        }

        if dry_run:
            entry["action"] = "dry-run"
            entry["clearRange"] = {
                "rowFrom": write_start_row,
                "rowTo": tactive_row_to if tactive_row_to > write_start_row else write_start_row,
                "colFrom": write_start_col,
                "colTo": effective_clear_col_to,
            } if clear_before_write else None
            entry["sampleData"] = filtered_rows[:3] if filtered_rows else []
            results.append(entry)
            continue

        # 清空
        if clear_before_write and tactive_row_to > write_start_row:
            try:
                clear_range(client, page_id, tws_id, write_start_row, tactive_row_to, write_start_col, effective_clear_col_to)
            except Exception as exc:
                entry["clearError"] = str(exc)
                _log("warning", f"clear failed for {tname}: {exc}")

        # 写入
        if filtered_rows:
            try:
                write_range(client, page_id, tws_id, filtered_rows, write_start_row, write_start_col, clear_empty=True)
                entry["status"] = "success"
            except Exception as exc:
                entry["status"] = "write_error"
                entry["error"] = str(exc)
                _log("error", f"write failed for {tname}: {exc}")
        else:
            entry["status"] = "no_data"

        # 保护范围
        if protection_data and entry.get("status") == "success":
            try:
                set_protection(client, page_id, tws_id, protection_data)
                entry["protection"] = "applied"
            except Exception as exc:
                entry["protection"] = f"failed: {exc}"
                _log("warning", f"protection failed for {tname}: {exc}")

        results.append(entry)

    # Step 8: 验证
    verification = None
    if verify and not dry_run and target_metas:
        first_ok = next((r for r in results if r.get("status") == "success"), None)
        if first_ok:
            tname = first_ok["targetSheet"]
            try:
                fresh_sheets = get_all_worksheets(client, page_id)
                tmeta = find_sheet_by_name(fresh_sheets, tname)
            except ValueError:
                tmeta = find_sheet_by_name(all_sheets, tname)
            try:
                verify_data = read_range_as_table(
                    client, page_id, tmeta["sheetId"],
                    write_start_row,
                    write_start_row + min(2, first_ok["rowsToWrite"] - 1),
                    write_start_col, write_start_col + len(columns) - 1,
                )
                verification = {
                    "sheet": tname,
                    "sampleData": verify_data,
                    "expectedColumns": columns,
                }
            except Exception as exc:
                verification = {"sheet": tname, "error": f"verification read failed: {exc}"}

    return {
        "status": "success",
        "summary": f"已按 '{filter_column}' 列分拆: {len(results)} 个目标工作表, 共 {len(source_data_rows)} 行源数据",
        "pageId": page_id,
        "sourceSheet": source_sheet,
        "filterColumn": filter_column,
        "columns": columns,
        "writeStartRow": write_start_row,
        "clearBeforeWrite": clear_before_write,
        "totalSourceRows": len(source_data_rows),
        "targets": results,
        "verification": verification,
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="JoySpace Sheet Split Pipeline")
    parser.add_argument("--params", default="{}", help="JSON 格式参数（统一入口路由）")
    parser.add_argument("--token", help="SSO Token")
    parser.add_argument("--team-id", help="Team ID")
    parser.add_argument("--page-url", required=True, help="JoySpace Sheets page URL or ID")
    parser.add_argument("--source-sheet", required=True, help="Source worksheet name")
    parser.add_argument("--filter-column", required=True, help="Column name to filter by")
    parser.add_argument("--columns", required=True, help="Comma-separated column names to include")
    parser.add_argument("--target-sheets", help="Comma-separated target sheet names (auto-detect if omitted)")
    parser.add_argument("--header-row", type=int, default=0, help="Header row index (0-based, default=0)")
    parser.add_argument("--write-start-row", type=int, default=0, help="Row to start writing (0-based, default=0)")
    parser.add_argument("--write-start-col", type=int, default=0, help="Column to start writing (0-based, default=0)")
    parser.add_argument("--no-clear", action="store_true", help="Skip clearing target before write")
    parser.add_argument("--clear-col-to", type=int, help="Override clear range col_to")
    parser.add_argument("--dry-run", action="store_true", help="Preview without writing")
    parser.add_argument("--no-verify", action="store_true", help="Skip verification after write")
    parser.add_argument("--protection-json", help="JSON for protection ranges (applied after write)")
    parser.add_argument("--protection-file", help="File with protection JSON")
    args = parser.parse_args()

    # 支持 --params JSON 路由模式
    if args.params and args.params != "{}":
        try:
            p = json.loads(args.params)
        except json.JSONDecodeError:
            p = {}
        for attr, key in [
            ("page_url", "page_url"), ("source_sheet", "source_sheet"),
            ("filter_column", "filter_column"), ("columns", "columns"),
            ("target_sheets", "target_sheets"),
        ]:
            if not getattr(args, attr, None):
                setattr(args, attr, p.get(key))

    protection_data = None
    if args.protection_file:
        protection_data = json.loads(Path(args.protection_file).read_text(encoding="utf-8-sig"))
    elif args.protection_json:
        protection_data = json.loads(args.protection_json)

    target_list = [s.strip() for s in args.target_sheets.split(",")] if args.target_sheets else None
    col_list = [c.strip() for c in args.columns.split(",")]

    summary = run(
        args.page_url,
        args.source_sheet,
        args.filter_column,
        col_list,
        target_sheets=target_list,
        header_row=args.header_row,
        write_start_row=args.write_start_row,
        write_start_col=args.write_start_col,
        clear_before_write=not args.no_clear,
        clear_col_to=args.clear_col_to,
        dry_run=args.dry_run,
        verify=not args.no_verify,
        protection_data=protection_data,
        sso_token=args.token,
    )
    print(json.dumps(summary, ensure_ascii=False, indent=2))
    return 0 if summary.get("status") != "error" else 1


if __name__ == "__main__":
    try:
        sys.exit(main())
    except SystemExit:
        raise
    except Exception as exc:
        print(json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False), file=sys.stderr)
        sys.exit(1)
