from __future__ import annotations

import hashlib
from pathlib import Path
from typing import Tuple

import pandas as pd

from db.repositories import SqlAlchemyIngestRepository
from db.overrides import apply_overrides
from db.seed import seed_attribute_registry_if_available
from db.services import build_dataframe_from_snapshots, ingest_plytix_dataframe
from db.session import get_session
from db.url_shortener import shorten_image_urls_in_df
from normalize import normalize_plytix_df
from settings import MagentoNormalizeConfig, load_db_config, shorten_image_urls_enabled


def _hash_bytes(content: bytes) -> str:
    return hashlib.sha256(content).hexdigest()


def ingest_and_normalize_from_db(
    df: pd.DataFrame,
    *,
    file_name: str,
    file_bytes: bytes,
    cfg: MagentoNormalizeConfig,
) -> Tuple[pd.DataFrame, pd.DataFrame]:
    file_hash = _hash_bytes(file_bytes)
    with get_session() as session:
        db_cfg = load_db_config()
        seed_attribute_registry_if_available(
            session,
            Path(db_cfg.attribute_registry_path),
        )
        repo = SqlAlchemyIngestRepository(session)
        attribute_defs = repo.load_attribute_def_index()
        allowed_codes = set(attribute_defs.keys())
        attribute_options = repo.load_attribute_option_index()
        ingest_id, skus = ingest_plytix_dataframe(
            repo,
            df,
            file_name=file_name,
            file_hash=file_hash,
            keep_cols=cfg.keep_cols,
            hardcoded_additional=cfg.hardcoded_additional,
            allowed_attribute_codes=allowed_codes,
        )
        session.flush()
        snapshots = repo.load_current_snapshots(skus)
        snapshot_df = build_dataframe_from_snapshots(snapshots)
        overrides = repo.load_overrides_for_skus(skus)
        snapshot_df = apply_overrides(snapshot_df, overrides)
        normalized_df, quarantine_df = normalize_plytix_df(
            snapshot_df,
            cfg,
            allowed_attribute_codes=allowed_codes,
            allowed_attribute_options=attribute_options,
            enforce_required_name=False,
        )
        if shorten_image_urls_enabled():
            normalized_df = shorten_image_urls_in_df(normalized_df, repo)
        return normalized_df, quarantine_df
