"""Export per-system attribute cleanup/addition recommendations.

CLI:
    python -m app.jobs.export_attribute_action_plan --output attribute_action_plan.csv
"""

from __future__ import annotations

import argparse
import csv
import sys


def run_export_attribute_action_plan(output_path: str, *, include_magento: bool = True) -> dict:
    from db.attribute_mapping import build_attribute_action_plan
    from db.session import get_session

    with get_session() as session:
        rows = build_attribute_action_plan(session, include_magento=include_magento)

    fieldnames = [
        "system",
        "action",
        "attribute_code",
        "source_system",
        "source_label",
        "source_column_key",
        "canonical_code",
        "target_scope",
        "purpose",
        "sku_count",
        "sample_values",
        "reason",
    ]
    with open(output_path, "w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)

    return {"status": "ok", "output": output_path, "rows": len(rows)}


def main() -> int:
    parser = argparse.ArgumentParser(description="Export attribute action plan CSV")
    parser.add_argument("--output", required=True, help="Output CSV path")
    parser.add_argument("--exclude-magento", action="store_true", help="Exclude Magento source/registry attributes")
    args = parser.parse_args()

    result = run_export_attribute_action_plan(args.output, include_magento=not args.exclude_magento)
    print(f"Attribute action plan export complete: output={result['output']} rows={result['rows']}")
    return 0


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