import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createAgent, deleteAgent, getAgent, listAgents, listArtifacts, setAgentToolPermission, upsertSchedule, appendAudit } from '../lib/runtime.js';
import { addTaskComment, createAgentRun, createTask, markAgentRunFinished, markAgentRunWaitingApproval, updateTask } from '../lib/delegation.js';
import { getDb, nowIso } from '../lib/db.js';
import { ROOT, WORKSPACE, AGENTS_DIR, ARTIFACTS_DIR, REPORTS_DIR } from '../lib/paths.js';
import { writeAgentSkills } from '../lib/agent-skills.js';

function within(child, parent) {
  const rel = path.relative(parent, child);
  return rel === '' || (!!rel && !rel.startsWith('..') && !path.isAbsolute(rel));
}

function deleteArtifactFile(filePath) {
  if (!filePath) return false;
  const abs = path.resolve(ROOT, filePath);
  for (const allowed of [ARTIFACTS_DIR, REPORTS_DIR]) {
    if (within(abs, allowed) && fs.existsSync(abs) && fs.statSync(abs).isFile()) {
      fs.unlinkSync(abs);
      return true;
    }
  }
  return false;
}

function installImageTool({ name, title, description, category = 'image_generation', risk = 'medium', env = [], enabled = true }) {
  const db = getDb();
  const now = nowIso();
  db.prepare(`
    INSERT INTO tool_installations (name, title, description, category, enabled, risk_level, required_env, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ON CONFLICT(name) DO UPDATE SET
      title=excluded.title,
      description=excluded.description,
      category=excluded.category,
      enabled=excluded.enabled,
      risk_level=excluded.risk_level,
      required_env=excluded.required_env,
      updated_at=excluded.updated_at
  `).run(name, title, description, category, enabled ? 1 : 0, risk, JSON.stringify(env), now, now);
}

function villaSkills(agent, sections) {
  return `# ${agent.name} Skills

## Villa 515 business context
Villa 515 is a luxury Jumeirah destination where niche perfumery, bespoke scent creation, workshops, fragrance-led hospitality, private dining, gifting, and WhatsApp concierge service should operate as one premium experience loop.

## Mission
${agent.mission}

## Primary outcomes
${sections.outcomes.map(x => `- ${x}`).join('\n')}

## Daily/weekly playbook
${sections.playbook.map(x => `- ${x}`).join('\n')}

## Tool policy
- Read/search/extract public web and safe local project files automatically where permission is set to auto.
- Draft marketing, WhatsApp, email, and social copy only; external sends/posts/deploys require owner approval.
- Image generation must create prompt packs, provider recommendation, and approval request before spend or publish.
- Store durable outputs in madarX artifacts/reports and summarize owner decisions in memory only when lasting.

## Brand voice
Premium, sensory, warm, precise, Dubai-luxury, never generic AI hype. Use perfume notes, ritual, hospitality, private experience, and concierge language.
`;
}

const imageProviderNotes = [
  'Open source local: ComfyUI running FLUX.1-schnell or SDXL for fast low-cost concept boards on the Mac/local GPU.',
  'Google: Imagen / Gemini image generation for polished luxury campaign visuals when Google API credentials are available.',
  'Chinese provider: Alibaba Tongyi Wanxiang for image generation and Chinese-market visual style exploration.',
  'Chinese provider: ByteDance Seedream 4.0 for high-quality campaign/editorial image concepts.',
  'Chinese/open model: Kuaishou Kolors for portrait/product/lifestyle experiments through local or hosted inference.',
  'Commercial fallback: OpenAI gpt-image-1 for reliable English prompt-to-image campaign comps.'
];

const agents = [
  {
    id: 'villa515-main-orchestrator',
    name: 'Villa 515 Main Orchestrator',
    type: 'orchestrator', engine: 'anthropic', model: 'claude-sonnet-4-5', schedule: 'daily 07:45',
    tools: ['web_search','web_extract','file_read','directory_list','process_poll'],
    mission: 'Own the Villa 515 business operating rhythm: assign work to specialist agents, consolidate the owner briefing, and keep every action approval-gated.',
    outcomes: ['One daily owner briefing with priorities, risks, and approvals needed.', 'Clear handoff between marketing, concierge, website, commerce, and creative agents.', 'No external posting/sending/deploying without owner approval.'],
    playbook: ['At 07:45 collect yesterday signals, today bookings/events, content needs, and agent statuses.', 'Route tasks to specialist agents and produce a concise owner dashboard summary.', 'Escalate blockers: missing credentials, approvals, urgent customer/influencer issues.'],
    permissions: { web_search: 'auto', web_extract: 'auto', file_read: 'auto', directory_list: 'auto' }
  },
  {
    id: 'villa515-competitor-intelligence',
    name: 'Villa 515 Competitor Intelligence Agent',
    type: 'research', engine: 'ollama', model: 'qwen3.5:latest', schedule: 'daily 08:00',
    tools: ['web_search','web_extract','file_read','directory_list'],
    mission: 'Track Dubai niche perfumery, fragrance workshops, luxury hospitality, experiential dining, and premium gifting competitors.',
    outcomes: ['Daily competitor signal report.', 'Opportunity list for Scent of the Week, workshops, private dining, and gifting.', 'Screenshots/URLs queue for the owner or creative team to review.'],
    playbook: ['Search Villa 515, Dubai perfume workshop, bespoke scent Dubai, Jumeirah fragrance, experiential dining Dubai, and luxury gifting Dubai.', 'Separate signals into competitor movement, content angle, offer/pricing, event/workshop, and partnership opportunity.', 'Recommend three owner actions max.'],
    permissions: { web_search: 'auto', web_extract: 'auto', file_read: 'auto' }
  },
  {
    id: 'villa515-marketing-strategist',
    name: 'Villa 515 Marketing Strategist Agent',
    type: 'marketing', engine: 'anthropic', model: 'claude-sonnet-4-5', schedule: 'daily 09:00',
    tools: ['web_search','web_extract','file_read','file_write'],
    mission: 'Turn market signals into campaigns for Instagram, TikTok, WhatsApp, workshops, restaurant moments, and perfumery commerce.',
    outcomes: ['Daily content priorities and captions.', 'Weekly campaign calendar.', 'Draft-only WhatsApp/SMS/email campaign copy.'],
    playbook: ['Convert competitor intelligence into 3 content pillars and 5 draft posts.', 'Create a WhatsApp concierge angle for each campaign.', 'Tie every campaign to booking, workshop seat, private event, or gifting conversion.'],
    permissions: { web_search: 'auto', web_extract: 'auto', file_read: 'auto', file_write: 'approval_required' }
  },
  {
    id: 'villa515-creative-image-studio',
    name: 'Villa 515 Creative Image Studio Agent',
    type: 'creative', engine: 'anthropic', model: 'claude-sonnet-4-5', schedule: 'daily 10:30',
    tools: ['image_comfyui_flux_schnell','image_google_imagen','image_alibaba_wanxiang','image_bytedance_seedream','image_kuaishou_kolors','image_openai_gpt_image','file_read','file_write'],
    mission: 'Create luxury image prompt packs and provider recommendations for Villa 515 campaigns before any image-generation spend or publish step.',
    outcomes: ['Approved image brief and prompt matrix for each campaign.', 'Provider choice: local open-source first, then Google/Chinese/commercial options as needed.', 'Visual QA notes for generated images against Villa 515 luxury brand standards.'],
    playbook: ['Default to ComfyUI + FLUX.1-schnell/SDXL for cheap concept drafts.', 'Use Google Imagen/Gemini image generation for polished hero imagery when available.', 'Use Alibaba Tongyi Wanxiang, ByteDance Seedream, and Kuaishou Kolors for Chinese-market aesthetics, product/lifestyle variations, and provider benchmarking.', 'Never generate or publish images without owner-approved brief/provider/cost.'],
    extra: imageProviderNotes,
    permissions: { image_comfyui_flux_schnell: 'approval_required', image_google_imagen: 'approval_required', image_alibaba_wanxiang: 'approval_required', image_bytedance_seedream: 'approval_required', image_kuaishou_kolors: 'approval_required', image_openai_gpt_image: 'approval_required', file_read: 'auto', file_write: 'approval_required' }
  },
  {
    id: 'villa515-whatsapp-concierge',
    name: 'Villa 515 WhatsApp Concierge Agent',
    type: 'concierge', engine: 'anthropic', model: 'claude-sonnet-4-5', schedule: 'daily 11:00',
    tools: ['file_read','file_write','web_search'],
    mission: 'Draft high-touch WhatsApp concierge flows for workshop bookings, private dining, fragrance consultations, reorder reminders, and VIP follow-up.',
    outcomes: ['Draft message sequences for each lead/booking moment.', 'Owner approval queue for any outbound send.', 'Concierge scripts that feel personal, premium, and sensory.'],
    playbook: ['Prepare pre-visit scent quiz, reminder, arrival, post-visit reorder, and private-event follow-up scripts.', 'Segment messages by workshop guest, perfume buyer, dining guest, VIP/private event, and influencer.', 'Never send directly; mark every external send as approval-required.'],
    permissions: { file_read: 'auto', file_write: 'approval_required', web_search: 'auto' }
  },
  {
    id: 'villa515-workshop-events',
    name: 'Villa 515 Workshop & Events Agent',
    type: 'events', engine: 'ollama', model: 'qwen3.5:latest', schedule: 'daily 12:00',
    tools: ['web_search','web_extract','file_read','file_write'],
    mission: 'Package fragrance workshops, corporate/private scent sessions, restaurant pairings, and VIP events into bookable offers.',
    outcomes: ['Workshop/event calendar ideas.', 'Offer packaging and operational checklist.', 'Lead magnets and follow-up content for bookings.'],
    playbook: ['Check upcoming dates, campaign moments, holidays, corporate gifting seasons, and local luxury events.', 'Draft event packages: private scent majlis, couple workshop, corporate gifting lab, scent-paired dinner.', 'Hand marketing hooks to Marketing Strategist and concierge follow-up to WhatsApp Concierge.'],
    permissions: { web_search: 'auto', web_extract: 'auto', file_read: 'auto', file_write: 'approval_required' }
  },
  {
    id: 'villa515-commerce-gifting',
    name: 'Villa 515 Commerce & Gifting Agent',
    type: 'commerce', engine: 'ollama', model: 'qwen3.5:latest', schedule: 'daily 14:00',
    tools: ['web_search','web_extract','file_read','file_write'],
    mission: 'Build perfume/gifting bundles, reorder loops, personalization offers, and seasonal commerce opportunities.',
    outcomes: ['Bundle concepts and offer copy.', 'Gifting calendar and personalization ideas.', 'Upsell/cross-sell notes for concierge.'],
    playbook: ['Identify gifting triggers: birthdays, anniversaries, Eid, corporate gifting, private dinner hosting, workshop follow-up.', 'Draft bundles with scent notes, packaging language, delivery promise, and WhatsApp CTA.', 'Flag inventory/data requirements without pretending to know stock levels.'],
    permissions: { web_search: 'auto', web_extract: 'auto', file_read: 'auto', file_write: 'approval_required' }
  },
  {
    id: 'villa515-website-seo-qa',
    name: 'Villa 515 Website SEO & QA Agent',
    type: 'website', engine: 'claude-code', model: 'sonnet', schedule: 'weekly Monday 09:30',
    tools: ['web_search','web_extract','file_read','directory_list','terminal_run','process_start','process_poll','file_write','file_patch','vercel_list_projects','vercel_list_deployments','vercel_create_deployment'],
    mission: 'Inspect the Villa 515 landing page, SEO, campaign pages, performance, and conversion copy; prepare Claude Code implementation plans and approval-gated deploy requests.',
    outcomes: ['Weekly website QA report.', 'SEO/content improvement backlog.', 'Approval-gated implementation/deploy plan.'],
    playbook: ['Review landing page messaging for perfumery, workshops, hospitality, private events, WhatsApp CTA, and luxury trust signals.', 'Run local QA/build checks before proposing code changes.', 'Deploy only after explicit owner approval.'],
    permissions: { web_search: 'auto', web_extract: 'auto', file_read: 'auto', directory_list: 'auto', terminal_run: 'approval_required', process_start: 'approval_required', process_poll: 'auto', file_write: 'approval_required', file_patch: 'approval_required', vercel_list_projects: 'approval_required', vercel_list_deployments: 'approval_required', vercel_create_deployment: 'approval_required' }
  },
  {
    id: 'villa515-reputation-influencer-pr',
    name: 'Villa 515 Reputation & Influencer PR Agent',
    type: 'pr', engine: 'ollama', model: 'qwen3.5:latest', schedule: 'daily 16:00',
    tools: ['web_search','web_extract','file_read','file_write'],
    mission: 'Monitor public reputation signals, influencer partnership opportunities, reviews, local press, and luxury/community collaborations.',
    outcomes: ['Daily PR/reputation watch.', 'Influencer shortlist and outreach draft.', 'Review-response drafts for owner approval.'],
    playbook: ['Search public web/social/news mentions for Villa 515, relevant Dubai fragrance/luxury creators, and event/community opportunities.', 'Draft outreach only; never DM/email/post without approval.', 'Escalate negative reviews, VIP issues, or press opportunities immediately.'],
    permissions: { web_search: 'auto', web_extract: 'auto', file_read: 'auto', file_write: 'approval_required' }
  }
];

// 1) Delete only existing current agents + their schedules/permissions/files.
const db = getDb();
db.prepare("DELETE FROM task_events WHERE task_id IN (SELECT id FROM tasks WHERE project_id = 'villa515-poc')").run();
db.prepare("DELETE FROM task_comments WHERE task_id IN (SELECT id FROM tasks WHERE project_id = 'villa515-poc')").run();
db.prepare("DELETE FROM agent_run_events WHERE task_id IN (SELECT id FROM tasks WHERE project_id = 'villa515-poc')").run();
db.prepare("DELETE FROM agent_runs WHERE task_id IN (SELECT id FROM tasks WHERE project_id = 'villa515-poc')").run();
db.prepare("DELETE FROM tasks WHERE project_id = 'villa515-poc'").run();
const existingAgents = listAgents();
const oldAgentIds = existingAgents.map(agent => agent.id);
for (const id of oldAgentIds) deleteAgent(id);
if (oldAgentIds.length) {
  const placeholders = oldAgentIds.map(() => '?').join(',');
  getDb().prepare(`DELETE FROM agent_tool_permissions WHERE agent_id IN (${placeholders})`).run(...oldAgentIds);
}

// 2) Delete only current artifacts listed in the active DB and their exact files under workspace artifacts/reports.
const existingArtifacts = listArtifacts(1000);
for (const artifact of existingArtifacts) {
  deleteArtifactFile(artifact.path);
  getDb().prepare('DELETE FROM artifacts WHERE id = ?').run(artifact.id);
}

// 3) Register image-generation providers as POC tools.
const imageTools = [
  { name: 'image_comfyui_flux_schnell', title: 'Image Gen · ComfyUI FLUX.1-schnell', description: 'Local/open-source image generation through ComfyUI using FLUX.1-schnell or SDXL for low-cost concept boards.', env: ['COMFYUI_URL'] },
  { name: 'image_google_imagen', title: 'Image Gen · Google Imagen/Gemini', description: 'Google image generation provider for polished luxury campaign hero imagery.', env: ['GOOGLE_AI_API_KEY'] },
  { name: 'image_alibaba_wanxiang', title: 'Image Gen · Alibaba Tongyi Wanxiang', description: 'Alibaba Cloud Tongyi Wanxiang image-generation provider for Chinese-market visual exploration.', env: ['ALIBABA_DASHSCOPE_API_KEY'] },
  { name: 'image_bytedance_seedream', title: 'Image Gen · ByteDance Seedream', description: 'ByteDance Seedream image-generation provider for editorial/product campaign concepts.', env: ['ARK_API_KEY'] },
  { name: 'image_kuaishou_kolors', title: 'Image Gen · Kuaishou Kolors', description: 'Kwai/Kuaishou Kolors open model/provider for portrait, product, and lifestyle visual experiments.', env: ['KOLORS_API_KEY'] },
  { name: 'image_openai_gpt_image', title: 'Image Gen · OpenAI GPT Image', description: 'Commercial fallback image-generation provider for reliable campaign comps.', env: ['OPENAI_API_KEY'] },
];
for (const tool of imageTools) installImageTool(tool);

// 4) Create Villa 515 POC agents, schedules, skills, and permissions.
for (const spec of agents) {
  const created = createAgent({
    id: spec.id, name: spec.name, type: spec.type, engine: spec.engine, model: spec.model,
    mission: spec.mission, schedule: spec.schedule, tools: spec.tools, approval: 'human-in-loop',
    memory: [
      'Villa 515 business context: luxury Jumeirah destination combining niche perfumery, workshops, hospitality/private dining, gifting, and WhatsApp concierge.',
      'POC rule: all external sends, posts, deploys, image-generation spend, and destructive local actions require owner approval.'
    ],
  });
  upsertSchedule({ agent_id: spec.id, name: spec.name, schedule: spec.schedule, action_kind: 'agent-tick', delivery: 'dashboard report + owner approval', approval: 'human-in-loop' });
  const skills = villaSkills(created.agent, { outcomes: spec.outcomes, playbook: [...spec.playbook, ...(spec.extra || [])] });
  writeAgentSkills(spec.id, skills);
  for (const [tool, mode] of Object.entries(spec.permissions)) setAgentToolPermission(spec.id, tool, mode);
}

// 5) Seed an operator-demo delegated workflow so the dashboard can show the full loop immediately.
const demoRoot = createTask({
  id: 'villa515-demo-daily-owner-briefing',
  project_id: 'villa515-poc',
  title: 'Villa 515 daily owner briefing',
  description: 'Main orchestrator coordinates specialist agents, summarizes today\'s priorities, and holds external actions for owner approval.',
  assignee_agent_id: 'villa515-main-orchestrator',
  created_by_user_id: 'ak@madarx.io',
  priority: 'urgent',
});
const demoChildren = [
  createTask({
    id: 'villa515-demo-competitor-signals',
    project_id: 'villa515-poc',
    parent_task_id: demoRoot.id,
    title: 'Collect Dubai luxury fragrance competitor signals',
    description: 'Research public competitor movement and return three actionable opportunities for today\'s briefing.',
    assignee_agent_id: 'villa515-competitor-intelligence',
    created_by_agent_id: 'villa515-main-orchestrator',
    priority: 'high',
  }),
  createTask({
    id: 'villa515-demo-whatsapp-approval',
    project_id: 'villa515-poc',
    parent_task_id: demoRoot.id,
    title: 'Draft VIP WhatsApp concierge follow-up for owner approval',
    description: 'Prepare a premium WhatsApp follow-up draft for workshop guests; do not send until approved.',
    assignee_agent_id: 'villa515-whatsapp-concierge',
    created_by_agent_id: 'villa515-main-orchestrator',
    priority: 'high',
  }),
  createTask({
    id: 'villa515-demo-image-provider-blocker',
    project_id: 'villa515-poc',
    parent_task_id: demoRoot.id,
    title: 'Prepare Scent of the Week visual prompt pack',
    description: 'Create a prompt matrix and provider recommendation before image spend.',
    assignee_agent_id: 'villa515-creative-image-studio',
    created_by_agent_id: 'villa515-main-orchestrator',
    priority: 'medium',
  }),
];
addTaskComment(demoRoot.id, { author_agent_id: 'villa515-main-orchestrator', body: 'Demo workflow seeded: competitor research, concierge approval, and image-provider blocker are visible in Tasks, Activity, and the Operator Command Center.' });
updateTask(demoChildren[0].id, { status: 'done', actor_type: 'agent', actor_id: 'villa515-competitor-intelligence' });
addTaskComment(demoChildren[0].id, { author_agent_id: 'villa515-competitor-intelligence', body: 'Completed mock competitor scan and attached briefing notes for the orchestrator.' });
const approvalRun = createAgentRun({ agent_id: 'villa515-whatsapp-concierge', task_id: demoChildren[1].id, trigger_source: 'villa515-poc-reset' });
markAgentRunWaitingApproval(approvalRun.id, { message: 'Owner approval required before sending the VIP WhatsApp draft.', payload: { channel: 'whatsapp', risk: 'external_send' } });
const failedRun = createAgentRun({ agent_id: 'villa515-creative-image-studio', task_id: demoChildren[2].id, trigger_source: 'villa515-poc-reset' });
markAgentRunFinished(failedRun.id, { status: 'failed', error: 'Image provider credentials are not configured for demo generation.' });
updateTask(demoChildren[2].id, { status: 'blocked', blocked_reason: 'Choose/configure an approved image provider before generation.', actor_type: 'agent', actor_id: 'villa515-creative-image-studio' });

appendAudit({
  type: 'villa515.poc.reset',
  summary: 'Reset current agents/artifacts and created Villa 515 POC agent operating system',
  status: 'complete',
  meta: { deleted_agents: oldAgentIds, deleted_artifacts: existingArtifacts.map(a => a.id), created_agents: agents.map(a => a.id), image_tools: imageTools.map(t => t.name), demo_tasks: [demoRoot.id, ...demoChildren.map(t => t.id)] }
});

console.log(JSON.stringify({
  deleted_agents: oldAgentIds,
  deleted_artifacts: existingArtifacts.map(a => ({ id: a.id, title: a.title, path: a.path })),
  created_agents: agents.map(a => ({ id: a.id, name: a.name, schedule: a.schedule, engine: a.engine, model: a.model })),
  image_tools: imageTools.map(t => t.name),
  demo_tasks: [demoRoot, ...demoChildren].map(task => ({ id: task.id, title: task.title, assignee_agent_id: task.assignee_agent_id, status: task.status })),
  demo_runs: [{ id: approvalRun.id, status: 'waiting_approval' }, { id: failedRun.id, status: 'failed' }],
  workspace_agents_dir: path.relative(ROOT, AGENTS_DIR),
}, null, 2));

process.exit(0);
