import { REGION_TREE } from './constants';

const PROVINCES = [
  '北京市', '天津市', '河北省', '山西省', '内蒙古自治区',
  '上海市', '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省',
  '广东省', '广西壮族自治区', '海南省',
  '河南省', '湖北省', '湖南省',
  '辽宁省', '吉林省', '黑龙江省',
  '重庆市', '四川省', '贵州省', '云南省', '西藏自治区',
  '陕西省', '甘肃省', '青海省', '宁夏回族自治区', '新疆维吾尔自治区',
];

const MUNICIPALITIES = new Set(['北京市', '天津市', '上海市', '重庆市']);

export function parseAddressToRegion(fullAddress: string): {
  cityProvince: string;
  cityName: string;
  detailAddress: string;
} {
  const text = fullAddress.trim();
  if (!text) return { cityProvince: '', cityName: '', detailAddress: '' };

  const province = PROVINCES.find((item) => text.startsWith(item));
  if (!province) return { cityProvince: '', cityName: '', detailAddress: text };

  const node = REGION_TREE.find((item) => item.province === province);
  if (!node) return { cityProvince: '', cityName: '', detailAddress: text };

  if (MUNICIPALITIES.has(province)) {
    const municipalityCity = node.cities.find((city) => city === province) ?? node.cities[0] ?? '';
    const detailAddress = text.slice(province.length).trim() || text;
    return { cityProvince: province, cityName: municipalityCity, detailAddress };
  }

  const rest = text.slice(province.length);
  const sortedCities = [...node.cities].sort((a, b) => b.length - a.length);
  const matchedCity = sortedCities.find((item) => rest.startsWith(item));
  const cityMatch = matchedCity ? null : rest.match(/^([\u4e00-\u9fa5]+?(?:市|区|州|盟|县))/);
  const city = matchedCity ?? cityMatch?.[1] ?? '';
  const detailAddress = city ? rest.slice(city.length).trim() : rest.trim();

  return {
    cityProvince: province,
    cityName: city,
    detailAddress: detailAddress || text,
  };
}

export function formatProvinceCity(cityProvince: string, cityName: string): string {
  if (!cityProvince) return '';
  if (!cityName || cityName === cityProvince) return cityProvince;
  return `${cityProvince}-${cityName}`;
}
