"""Import the full Plytix attribute catalog/list from CSV.

CLI:
    python -m app.jobs.import_plytix_attributes --file plytix_attributes.csv
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import pandas as pd


def run_import_plytix_attributes(
    file_path: str,
    *,
    source_label: str = "plytix",
    exclude_shopify: bool = True,
) -> dict:
    from db.plytix_attributes import import_plytix_attribute_catalog_dataframe
    from db.session import get_session

    path = Path(file_path)
    if not path.exists() or not path.is_file():
        return {"status": "failed", "error": f"File not found: {file_path}"}
    if path.suffix.lower() != ".csv":
        return {"status": "failed", "error": "Only CSV files are supported"}

    try:
        df = pd.read_csv(path, dtype=str, keep_default_na=False)
    except Exception as exc:
        return {"status": "failed", "error": f"Failed to read CSV: {exc}"}

    exclude_hints = ("shopify",) if exclude_shopify else ()
    with get_session() as session:
        stats = import_plytix_attribute_catalog_dataframe(
            session,
            df,
            source_label=source_label,
            exclude_destination_hints=exclude_hints,
        )
        attr_def_count = sync_catalog_to_attribute_def(session, source_label=source_label)
        session.commit()
    return {
        "status": "ok",
        "file": str(path),
        "source_label": source_label,
        "attribute_def_synced": attr_def_count,
        **stats,
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="Import Plytix attribute catalog CSV")
    parser.add_argument("--file", required=True, help="Plytix attribute CSV path")
    parser.add_argument("--source-label", default="plytix", help="Catalog source label")
    parser.add_argument(
        "--include-shopify",
        action="store_true",
        help="Keep Shopify connector attributes in the catalog (default: excluded)",
    )
    args = parser.parse_args()

    result = run_import_plytix_attributes(
        args.file,
        source_label=args.source_label,
        exclude_shopify=not args.include_shopify,
    )
    if result.get("status") != "ok":
        print(result.get("error", "unknown error"), file=sys.stderr)
        return 1
    print(
        "Plytix attribute import complete: "
        f"input_rows={result.get('input_rows', 0)}, "
        f"input_columns={result.get('input_columns', 0)}, "
        f"upserted={result.get('upserted', 0)}, "
        f"skipped={result.get('skipped', 0)}, "
        f"duplicates_merged={result.get('duplicates_merged', 0)}"
    )
    return 0


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