import fs from 'node:fs';
import path from 'node:path';

const BASE =
  'https://raw.githubusercontent.com/arco-design/arco-design-pro-vue/main/arco-design-pro-vite/src';

const vueFiles = [
  'views/visualization/multi-dimension-data-analysis/components/content-publishing-source.vue',
  'views/user/info/components/my-project.vue',
  'views/user/info/components/my-team.vue',
  'views/user/setting/components/enterprise-certification.vue',
];

async function download(relPath) {
  const res = await fetch(`${BASE}/${relPath}`);
  if (!res.ok) throw new Error(`${relPath}: HTTP ${res.status}`);
  return res.text();
}

function patchForProject(content, relPath) {
  let text = content;

  if (relPath.includes('my-project.vue')) {
    text = text.replace(
      "import { queryMyProjectList, MyProjectRecord } from '@/api/user-center';",
      "import { type MyProjectRecord, queryMyProjectList } from '@/api/user';",
    );
    text = text.replace(/\{\{ project\.contributors \}\}\s*/g, '');
  }

  if (relPath.includes('my-team.vue')) {
    text = text.replace(
      "import { queryMyTeamList, MyTeamRecord } from '@/api/user-center';",
      "import { type MyTeamRecord, queryMyTeamList } from '@/api/user';",
    );
  }

  if (relPath.includes('enterprise-certification.vue')) {
    text = text.replace(
      "import { EnterpriseCertificationModel } from '@/api/user-center';",
      "import type { EnterpriseCertificationModel } from '@/api/user';",
    );
    text = text.replace(
      /type: Object as PropType<EnterpriseCertificationModel>/,
      'type: Object as PropType<EnterpriseCertificationModel>,',
    );
  }

  return text;
}

async function main() {
  for (const relPath of vueFiles) {
    let content = await download(relPath);
    content = patchForProject(content, relPath);
    const fullPath = path.join('src', relPath);
    fs.mkdirSync(path.dirname(fullPath), { recursive: true });
    fs.writeFileSync(fullPath, content, 'utf8');
    const hasCn = /[\u4e00-\u9fff]/.test(content);
    console.log(`OK ${relPath} (cn=${hasCn})`);
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
