"""Pull Plytix attribute definitions from the API into plytix_attribute_catalog + attribute_def.

Prefer CSV import when API access is unavailable:
    python -m app.jobs.import_plytix_attributes --file plytix_attributes.csv

CLI:
    python -m app.jobs.plytix_attributes_pull
"""

from __future__ import annotations

import argparse
import sys
from typing import Any, Dict, List, Optional

import pandas as pd

from db.source_imports import normalize_column_key


def run_plytix_attributes_pull(*, source_label: str = "plytix_api") -> Dict[str, Any]:
    from db.plytix_attributes import import_plytix_attribute_catalog_dataframe, sync_catalog_to_attribute_def
    from db.session import get_session
    from plytix.attribute_pull import attribute_row_from_api, fetch_plytix_attribute_definitions
    from plytix.client_factory import build_plytix_client
    from settings import load_plytix_api_config

    cfg = load_plytix_api_config()
    try:
        client = build_plytix_client(cfg)
        attributes = fetch_plytix_attribute_definitions(
            client,
            page_size=cfg.page_size,
            max_pages=cfg.max_pages,
            search_path=cfg.attributes_path,
        )
    except Exception as exc:
        return {
            "status": "failed",
            "error": (
                f"Plytix attribute API error: {exc}. "
                "Import your Plytix attribute export CSV instead via "
                "POST /api/source-imports/plytix/attributes/csv or "
                "python -m app.jobs.import_plytix_attributes --file <csv>"
            ),
        }
    if not attributes:
        return {
            "status": "failed",
            "error": (
                "No attributes returned from Plytix API. "
                "Upload the Plytix attribute overview CSV instead "
                "(Mappings → Upload Plytix attributes CSV)."
            ),
        }

    rows = [attribute_row_from_api(item) for item in attributes]
    rows = [row for row in rows if row]
    df = pd.DataFrame(rows)
    with get_session() as session:
        stats = import_plytix_attribute_catalog_dataframe(session, df, source_label=source_label)
        attr_def_count = sync_catalog_to_attribute_def(session, source_label=source_label)
        session.commit()
    return {
        "status": "ok",
        "source": "plytix_api",
        "attribute_count": len(rows),
        "attribute_def_synced": attr_def_count,
        **stats,
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="Pull Plytix attributes from API")
    parser.add_argument("--source-label", default="plytix_api")
    args = parser.parse_args()
    result = run_plytix_attributes_pull(source_label=args.source_label)
    if result.get("status") != "ok":
        print(result.get("error", "Plytix attribute pull failed"), file=sys.stderr)
        return 1
    print(
        "Plytix attributes pull complete: "
        f"upserted={result.get('upserted', 0)}, attribute_def_synced={result.get('attribute_def_synced', 0)}"
    )
    return 0


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