import { getMarketRent, getCityIntelligence } from './locationIntelligence'

export type RentVerdict = 'BELOW' | 'AT' | 'ABOVE'

export interface RentEstimate {
  fairRentPerSqm: number      // Median-Marktmiete als faire Benchmark
  askingRentPerSqm: number
  verdict: RentVerdict        // Angebot vs. Markt
  deltaPct: number            // +über / −unter Markt (gerundet)
  rationale: string
  confidence: 'LOW' | 'MEDIUM' | 'HIGH'
}

/**
 * Markt-Einschätzung der Angebotsmiete: Vergleich gegen die Median-Marktmiete
 * (aus Standort-Intelligence) plus Leerstand/Miettrend als Kontext. Deterministisch.
 */
export function estimateMarketRent(city: string, assetType: string, askingRentPerSqm: number): RentEstimate | null {
  const market = getMarketRent(city, assetType)
  const intel = getCityIntelligence(city)
  if (market == null || !intel || askingRentPerSqm <= 0) return null

  const fair = market
  const deltaPct = Math.round(((askingRentPerSqm - fair) / fair) * 100)
  const verdict: RentVerdict = deltaPct > 5 ? 'ABOVE' : deltaPct < -5 ? 'BELOW' : 'AT'
  const trendNote = `Miettrend ${intel.rentTrend12m >= 0 ? '+' : ''}${intel.rentTrend12m}% (12 M)`
  const verdictText =
    verdict === 'ABOVE' ? `Angebot ${deltaPct}% über Marktmedian.`
    : verdict === 'BELOW' ? `Angebot ${Math.abs(deltaPct)}% unter Marktmedian.`
    : 'Angebot marktkonform.'
  const rationale = `Median ${city}: CHF ${fair}/m² · Leerstand ${intel.vacancyRatePct}% · ${trendNote}. ${verdictText}`
  const confidence = intel.demandStrength === 'LOW' ? 'LOW' : intel.avgDaysOnMarket > 70 ? 'MEDIUM' : 'HIGH'

  return { fairRentPerSqm: fair, askingRentPerSqm, verdict, deltaPct, rationale, confidence }
}

/** Indexierter Vorschlag für den künftigen Preis (Pre-Market): Heutepreis × (1 + Miettrend). */
export function suggestFutureRent(city: string, currentRentPerSqm: number): number | null {
  const intel = getCityIntelligence(city)
  if (!intel || currentRentPerSqm <= 0) return null
  return Math.round(currentRentPerSqm * (1 + intel.rentTrend12m / 100))
}
