"""Export a dry-run channel attribute preview CSV.

CLI:
    python -m app.jobs.export_channel_preview --channel magento --output magento_preview.csv
"""

from __future__ import annotations

import argparse
import sys

import pandas as pd


def run_export_channel_preview(
    channel: str,
    output_path: str,
    *,
    limit: int | None = None,
    only_assigned: bool = True,
    connection_id: int | None = None,
) -> dict:
    from db.channel_exports import build_channel_attribute_preview
    from db.session import get_session

    with get_session() as session:
        rows = build_channel_attribute_preview(
            session,
            channel,
            limit=limit,
            only_assigned=only_assigned,
            connection_id=connection_id,
        )
    pd.DataFrame(rows).to_csv(output_path, index=False)
    return {"status": "ok", "channel": channel, "output": output_path, "rows": len(rows)}


def main() -> int:
    parser = argparse.ArgumentParser(description="Export dry-run channel attribute preview")
    parser.add_argument("--channel", required=True, choices=["magento", "shopify", "plytix"])
    parser.add_argument("--output", required=True, help="Output CSV path")
    parser.add_argument("--limit", type=int, default=None, help="Optional product limit")
    parser.add_argument("--connection-id", type=int, default=None, help="Optional dashboard/compat connection id")
    parser.add_argument(
        "--include-unassigned",
        action="store_true",
        help="Preview all active master SKUs, not just those assigned to the channel",
    )
    args = parser.parse_args()

    result = run_export_channel_preview(
        args.channel,
        args.output,
        limit=args.limit,
        only_assigned=not args.include_unassigned,
        connection_id=args.connection_id,
    )
    if result.get("status") != "ok":
        print(result.get("error", "unknown error"), file=sys.stderr)
        return 1
    print(
        "Channel preview export complete: "
        f"channel={result['channel']} output={result['output']} rows={result['rows']}"
    )
    return 0


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