from __future__ import annotations

import json
import logging
import os
from typing import Any, Dict

from .rules import load_features, match_features
from storage.s3_adapter import S3Storage
from storage.config import load_config_from_env

logger = logging.getLogger(__name__)


def lambda_handler(event, context):
    cfg = load_config_from_env()
    features_path = os.getenv("FEATURES_PATH", os.path.join("config", "features.yaml"))
    features_cfg = load_features(features_path)
    s3 = S3Storage(cfg, no_aws=False)
    records = event.get("records", [])
    outputs = []
    for rec in records:
        text = rec.get("extracted_text", "")
        url = rec.get("url", "")
        feats = match_features(text, features_cfg)
        payload = {"url": url, "features": feats}
        s3_uri = s3.put_json(cfg.s3_bucket_processed, "features", url, payload)
        outputs.append({"s3": s3_uri, "url": url})
    return {"statusCode": 200, "body": json.dumps({"count": len(outputs)})}


