"""Import a server-local product SEO CSV as a safe overlay.

CLI:
    python -m app.jobs.import_product_seo --file /path/to/product_seo.csv --dry-run
    python -m app.jobs.import_product_seo --file /path/to/product_seo.csv
"""

from __future__ import annotations

import argparse
import json
import logging
import sys
from pathlib import Path

import pandas as pd

logger = logging.getLogger(__name__)


def run_import_product_seo(file_path: str, *, source_label: str = "product_seo", dry_run: bool = False) -> dict:
    from db.master_catalog import import_master_sku_seo_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"}

    logger.info("Reading product SEO CSV: %s", path)
    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}"}

    with get_session() as session:
        result = import_master_sku_seo_dataframe(
            session,
            df,
            source_label=source_label,
            dry_run=dry_run,
        )
        if not dry_run:
            session.commit()

    return {"status": "ok", "file": str(path), "source_label": source_label, **result}


def main() -> int:
    parser = argparse.ArgumentParser(description="Import a product SEO CSV overlay")
    parser.add_argument("--file", required=True, help="Path to the product SEO CSV on the server")
    parser.add_argument("--source-label", default="product_seo", help="Import source label")
    parser.add_argument("--dry-run", action="store_true", help="Preview updates without writing")
    args = parser.parse_args()

    result = run_import_product_seo(args.file, source_label=args.source_label, dry_run=args.dry_run)
    if result.get("status") != "ok":
        print(result.get("error", "unknown error"), file=sys.stderr)
        return 1
    print(json.dumps(result, indent=2, sort_keys=True))
    return 0


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    sys.exit(main())
