"""Parser for TikTok Ads CSV exports."""

import pandas as pd

from mixlift.ingest.templates import PLATFORM_SIGNATURES


def parse_tiktok_csv(df: pd.DataFrame) -> pd.DataFrame:
    """Parse a TikTok Ads CSV into canonical format."""
    col_map = _find_columns(df)

    result = pd.DataFrame()
    result["date"] = pd.to_datetime(df[col_map["date"]])

    if col_map.get("campaign"):
        result["channel"] = df[col_map["campaign"]].str.strip()
    else:
        result["channel"] = "TikTok"

    result["spend"] = pd.to_numeric(df[col_map["spend"]], errors="coerce").fillna(0)
    result["impressions"] = (
        pd.to_numeric(df[col_map["impressions"]], errors="coerce").fillna(0).astype(int)
    )
    result["clicks"] = (
        pd.to_numeric(df[col_map["clicks"]], errors="coerce").fillna(0).astype(int)
    )

    if col_map.get("conversions"):
        result["conversions"] = (
            pd.to_numeric(df[col_map["conversions"]], errors="coerce").fillna(0).astype(int)
        )
    else:
        result["conversions"] = 0

    return result


def _find_columns(df: pd.DataFrame) -> dict[str, str]:
    lower_cols = {c.lower().strip(): c for c in df.columns}
    tiktok_cols = PLATFORM_SIGNATURES["tiktok"]["columns"]

    col_map = {}
    for field, aliases in tiktok_cols.items():
        for alias in aliases:
            if alias.lower() in lower_cols:
                col_map[field] = lower_cols[alias.lower()]
                break

    required = ["date", "spend", "impressions", "clicks"]
    missing = [f for f in required if f not in col_map]
    if missing:
        raise ValueError(f"TikTok Ads CSV missing required columns: {missing}")

    return col_map
