const { Client } = require('pg');
const fs = require('fs');
const path = require('path');
require('dotenv').config({ path: '/root/miaojingAI/.env.local' });
const root='/root/miaojingAI';
const c = new Client({ connectionString: process.env.LOCAL_DB_URL });
function walk(dir){ if(!fs.existsSync(dir)) return 0; let n=0; for(const e of fs.readdirSync(dir,{withFileTypes:true})){ const p=path.join(dir,e.name); n += e.isDirectory()?walk(p):1; } return n; }
(async()=>{ await c.connect(); const checks={};
checks.admin=(await c.query(`select p.id,p.email,p.role,p.membership_tier,p.is_active,u.password_hash is not null as has_password_hash from profiles p join auth.users u on u.id=p.id where p.email='admin@example.com'`)).rows;
checks.orphanWorks=(await c.query(`select count(*)::int as n from works w left join profiles p on p.id=w.user_id where p.id is null`)).rows[0].n;
checks.orphanCredits=(await c.query(`select count(*)::int as n from credit_transactions ct left join profiles p on p.id=ct.user_id where p.id is null`)).rows[0].n;
checks.orphanApiKeys=(await c.query(`select count(*)::int as n from user_api_keys k left join profiles p on p.id=k.user_id where p.id is null`)).rows[0].n;
checks.publicWorks=(await c.query(`select count(*)::int as n, count(*) filter (where result_url like '/api/local-storage/gallery/%')::int as gallery_url_count from works where is_public=true`)).rows[0];
checks.galleryFiles=walk(path.join(root,'local-storage','gallery'));
checks.localFiles=walk(path.join(root,'local-storage'));
console.log(JSON.stringify(checks,null,2)); await c.end(); })().catch(e=>{console.error(e);process.exit(1)});
