import { urlRules } from '../rules/url-rules.js';
import { resourceRules } from '../rules/resource-rules.js';
import { permissionRules } from '../rules/permission-rules.js';

// URL Analysis
export async function analyzeUrl(url, rules) {
  const urlObj = new URL(url);
  let riskScore = 0;
  const findings = [];

  // Check domain patterns
  for (const pattern of rules.domainPatterns) {
    if (pattern.test(urlObj.hostname)) {
      riskScore += rules.weights.domainPattern;
      findings.push({
        type: 'domainPattern',
        pattern: pattern.toString(),
        hostname: urlObj.hostname
      });
    }
  }

  // Check URL patterns
  for (const pattern of rules.urlPatterns) {
    if (pattern.test(urlObj.pathname)) {
      riskScore += rules.weights.urlPattern;
      findings.push({
        type: 'urlPattern',
        pattern: pattern.toString(),
        pathname: urlObj.pathname
      });
    }
  }

  // Check query parameters
  for (const param of rules.queryParams) {
    if (urlObj.searchParams.has(param)) {
      riskScore += rules.weights.queryParam;
      findings.push({
        type: 'queryParam',
        param: param,
        value: urlObj.searchParams.get(param)
      });
    }
  }

  // Check target domains
  if (rules.targetDomains.includes(urlObj.hostname)) {
    riskScore += rules.weights.targetDomain;
    findings.push({
      type: 'targetDomain',
      domain: urlObj.hostname
    });
  }

  // Check redirect patterns
  for (const pattern of rules.redirectPatterns) {
    if (pattern.test(url)) {
      riskScore += rules.weights.redirectPattern;
      findings.push({
        type: 'redirectPattern',
        pattern: pattern.toString(),
        url: url
      });
    }
  }

  return {
    isSuspicious: riskScore >= rules.thresholds.high,
    riskScore,
    findings,
    riskLevel: riskScore >= rules.thresholds.high ? 'high' :
               riskScore >= rules.thresholds.medium ? 'medium' : 'low'
  };
}

// Resource Analysis
export async function analyzeResource(details, rules) {
  let riskScore = 0;
  const findings = [];

  // Check file extension
  const extension = details.url.split('.').pop().toLowerCase();
  if (rules.suspiciousExtensions.includes(`.${extension}`)) {
    riskScore += rules.weights.extension;
    findings.push({
      type: 'extension',
      extension: `.${extension}`
    });
  }

  // Check MIME type
  if (details.type && rules.suspiciousMimeTypes.includes(details.type)) {
    riskScore += rules.weights.mimeType;
    findings.push({
      type: 'mimeType',
      mimeType: details.type
    });
  }

  // Check resource patterns
  for (const pattern of rules.resourcePatterns) {
    if (pattern.test(details.url)) {
      riskScore += rules.weights.resourcePattern;
      findings.push({
        type: 'resourcePattern',
        pattern: pattern.toString(),
        url: details.url
      });
    }
  }

  // Check domain
  const urlObj = new URL(details.url);
  for (const pattern of rules.suspiciousDomains) {
    if (pattern.test(urlObj.hostname)) {
      riskScore += rules.weights.domain;
      findings.push({
        type: 'domain',
        pattern: pattern.toString(),
        hostname: urlObj.hostname
      });
    }
  }

  // Check content type
  if (details.type && rules.suspiciousContentTypes.includes(details.type)) {
    riskScore += rules.weights.contentType;
    findings.push({
      type: 'contentType',
      contentType: details.type
    });
  }

  return {
    isSuspicious: riskScore >= rules.thresholds.high,
    riskScore,
    findings,
    riskLevel: riskScore >= rules.thresholds.high ? 'high' :
               riskScore >= rules.thresholds.medium ? 'medium' : 'low'
  };
}

// Permission Analysis
export async function checkPermissions(permissions, rules) {
  let riskScore = 0;
  const findings = [];

  // Check high-risk permissions
  const highRiskFound = permissions.filter(p => rules.highRiskPermissions.includes(p));
  if (highRiskFound.length > 0) {
    riskScore += highRiskFound.length * rules.weights.highRisk;
    findings.push({
      type: 'highRiskPermissions',
      permissions: highRiskFound
    });
  }

  // Check medium-risk permissions
  const mediumRiskFound = permissions.filter(p => rules.mediumRiskPermissions.includes(p));
  if (mediumRiskFound.length > 0) {
    riskScore += mediumRiskFound.length * rules.weights.mediumRisk;
    findings.push({
      type: 'mediumRiskPermissions',
      permissions: mediumRiskFound
    });
  }

  // Check suspicious combinations
  for (const combination of rules.suspiciousCombinations) {
    const found = combination.filter(p => permissions.includes(p));
    if (found.length === combination.length) {
      riskScore += rules.weights.suspiciousCombination;
      findings.push({
        type: 'suspiciousCombination',
        combination: combination
      });
    }
  }

  // Check categories
  const categoryMatches = {};
  for (const [category, perms] of Object.entries(rules.categories)) {
    const matches = perms.filter(p => permissions.includes(p));
    if (matches.length > 0) {
      categoryMatches[category] = matches;
      riskScore += rules.weights.categoryMatch;
    }
  }

  if (Object.keys(categoryMatches).length > 0) {
    findings.push({
      type: 'categoryMatches',
      matches: categoryMatches
    });
  }

  return {
    isSuspicious: riskScore >= rules.thresholds.high,
    riskScore,
    findings,
    riskLevel: riskScore >= rules.thresholds.high ? 'high' :
               riskScore >= rules.thresholds.medium ? 'medium' : 'low'
  };
} 