import { ScanFinding } from './types';
import pool from '../../db';

function trackComplianceUsage(params: {
  model: string;
  inputTokens: number;
  outputTokens: number;
  totalTokens: number;
  responseTimeMs: number;
  success: boolean;
  errorMessage?: string;
}) {
  pool.query(
    `INSERT INTO rm_api_usage (category, provider, model, input_tokens, output_tokens, total_tokens, response_time_ms, success, error_message)
     VALUES ('compliance', 'grok', $1, $2, $3, $4, $5, $6, $7)`,
    [params.model, params.inputTokens, params.outputTokens, params.totalTokens,
     params.responseTimeMs, params.success, params.errorMessage || null]
  ).catch(err => console.error('[api-usage] Compliance track failed:', err.message));
}

const GROK_API_KEY = process.env.GROK_API_KEY || '';
const GROK_API_URL = process.env.GROK_API_URL || 'https://api.x.ai/v1/chat/completions';
const GROK_MODEL = process.env.GROK_MODEL || 'grok-4-1-fast-reasoning';

const DEFAULT_VOICE_PROMPT = `You are the Rainmaker editorial voice — witty, playful, and slightly unhinged (in a fun way). You see sports through a weather lens.
Use weather/storm metaphors: radar, pressure systems, tailwinds, turbulence, barometric readings, storm fronts.
Use uncertainty language: "may", "could", "worth watching", "one angle", "keep an eye on".
NEVER be crude, profane, hateful, sexual, or insulting.
NEVER use gambling CTAs or certainty language.
NEVER tell users what to do — preserve free will.`;

export async function rewriteContent(
  originalText: string,
  findings: ScanFinding[],
  fieldName: string,
  voicePrompt?: string | null
): Promise<string | null> {
  if (!GROK_API_KEY) {
    console.error('[COMPLIANCE-REWRITE] No GROK_API_KEY configured');
    return null;
  }

  const violationList = findings
    .map(f => `- "${f.matchedText}" (rule: ${f.label}, severity: ${f.severity}, category: ${(f as any).category || 'unknown'})`)
    .join('\n');

  const systemPrompt = voicePrompt || DEFAULT_VOICE_PROMPT;

  const userPrompt = `The following ${fieldName} content contains compliance violations that MUST be completely removed or replaced.

VIOLATIONS FOUND:
${violationList}

ORIGINAL TEXT:
${originalText}

MANDATORY INSTRUCTIONS:
1. Remove EVERY listed violation — no exceptions. Each one must be gone from the output.
2. Replace gambling-promotional phrases with weather-themed editorial alternatives:
   - "lock" / "guaranteed" → "the radar's picking up interesting signals" or "conditions look intriguing"
   - "hammer" / "smash" → "keep an eye on" or "there's some weather building around this angle"
   - "risk-free" / "free money" → "no freebies in the wild—just context, signals, and a little chaos"
   - "best bet" → "most intriguing forecast" or "the barometer's favorite reading"
   - "chase losses" / "double down" → remove entirely or replace with "reassess the conditions"
3. Keep the same factual/analytical content — only change the promotional/certainty language
4. Maintain approximate length
5. Use uncertainty language: "may", "could", "worth watching", "one angle to consider"
6. Be witty and fun but NEVER crude, profane, sexual, or insulting
7. NEVER tell readers what to do — present information, let them decide
8. NEVER include any betting recommendations, picks, or probability claims
9. Return ONLY the rewritten text — no explanations, no wrappers, no code fences`;

  for (let attempt = 0; attempt < 2; attempt++) {
    try {
      const controller = new AbortController();
      const timeout = setTimeout(() => controller.abort(), 90000);
      const startMs = Date.now();

      const res = await fetch(GROK_API_URL, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${GROK_API_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          model: GROK_MODEL,
          messages: [
            { role: 'system', content: systemPrompt },
            { role: 'user', content: userPrompt },
          ],
          temperature: 0.6,
          max_tokens: 4000,
        }),
        signal: controller.signal,
      });

      clearTimeout(timeout);

      if (!res.ok) {
        const errText = await res.text();
        console.error(`[COMPLIANCE-REWRITE] Grok API error ${res.status}:`, errText);
        trackComplianceUsage({ model: GROK_MODEL, inputTokens: 0, outputTokens: 0, totalTokens: 0, responseTimeMs: Date.now() - startMs, success: false, errorMessage: `${res.status}` });
        if (attempt < 1) continue;
        return null;
      }

      const data = await res.json() as any;
      const usage = data.usage || {};
      trackComplianceUsage({ model: GROK_MODEL, inputTokens: usage.prompt_tokens || 0, outputTokens: usage.completion_tokens || 0, totalTokens: usage.total_tokens || 0, responseTimeMs: Date.now() - startMs, success: true });

      let content = data.choices?.[0]?.message?.content || '';
      // Strip any code fences
      content = content.replace(/```(?:html|json|text)?\s*/g, '').replace(/```\s*/g, '').trim();

      if (!content || content.length < 50) {
        throw new Error('Rewritten content too short');
      }

      return content;
    } catch (err) {
      console.error(`[COMPLIANCE-REWRITE] Attempt ${attempt + 1} failed:`, err);
      if (attempt < 1) {
        await new Promise(r => setTimeout(r, 2000));
        continue;
      }
      return null;
    }
  }

  return null;
}
