USE hahn;

DECLARE $param_dict AS Dict<String, String>;

$base_dir = IF(
  $param_dict["branch"] = "prod",
  "//home/vipplanners/sow",
  "//home/vipplanners/sow_dev" || '/' || $param_dict["branch"]
);

-- output
$result = $base_dir || '/' || "dict/sources/sprav_banner_max_legal";

$yson_opt = Yson::Options(false as Strict);

$parse_list_val = ($yson, $key) -> {
  $val = Yson::LookupString($yson, $key, $yson_opt);
  $vals = String::SplitToList($val, ',');
  RETURN ListMap($vals, String::Strip);
};

$client_permalink = (
SELECT
  ClientID AS client_id
, permalink
, count(*) AS cnt
FROM `//home/altay/y-direct/current-state/banners-to-permalink`
GROUP COMPACT BY
  ClientID
, permalink
);

DEFINE SUBQUERY $calc_val($key) AS
SELECT
  client_id
, MAX_BY(val, cnt) AS val_max_cnt
FROM (
  SELECT
    client_id
  , val
  , SUM(cnt) AS cnt
  FROM (
    SELECT
      cp.client_id AS client_id
    , cp.cnt AS cnt
    , $parse_list_val(c.legal_info, $key) AS vals
    FROM $client_permalink AS cp
    JOIN `//home/sprav/altay/prod/geosearch_snapshot/company` AS c
      ON cp.permalink = c.permalink
  )
  FLATTEN LIST BY vals AS val
  WHERE val > ''
  GROUP BY
    client_id
  , val
)
GROUP BY client_id
END DEFINE;

INSERT INTO $result WITH TRUNCATE
SELECT
  NVL(i.client_id, o.client_id) AS client_id
, i.val_max_cnt AS inn_max_cnt
, o.val_max_cnt AS ogrn_max_cnt
FROM $calc_val("inn") AS i
FULL JOIN $calc_val("ogrn") AS o
  ON i.client_id = o.client_id
ORDER BY client_id
;
