// sp-tools-homestead.js — Pidgey Homestead: Real Estate Tool Implementations
export async function executeHomesteadTool(name, args, _ui, _state) {
    const { setStatus, playAudioAlert } = _ui;
    const { config } = _state;

    switch (name) {
        case 'mortgage_calculator': {
            setStatus('🏠 Crunching mortgage numbers...');
            const price = args.home_price;
            const downPct = args.down_payment_percent || 20;
            const rate = args.interest_rate || 6.75;
            const term = args.loan_term_years || 30;
            const taxRate = args.annual_tax_rate || 1.1;
            const hoa = args.monthly_hoa || 0;

            const downPayment = price * (downPct / 100);
            const loanAmount = price - downPayment;
            const monthlyRate = (rate / 100) / 12;
            const numPayments = term * 12;

            const monthlyPI = monthlyRate > 0
                ? loanAmount * (monthlyRate * Math.pow(1 + monthlyRate, numPayments)) / (Math.pow(1 + monthlyRate, numPayments) - 1)
                : loanAmount / numPayments;

            const monthlyTax = (price * (taxRate / 100)) / 12;
            const monthlyInsurance = args.monthly_insurance || Math.round(price * 0.004 / 12);
            const pmi = downPct < 20 ? Math.round(loanAmount * 0.007 / 12) : 0;
            const totalPITI = monthlyPI + monthlyTax + monthlyInsurance + hoa + pmi;
            const totalInterest = (monthlyPI * numPayments) - loanAmount;

            const result = [
                `🏠 MORTGAGE CALCULATOR`,
                ``,
                `Home Price: $${price.toLocaleString()}`,
                `Down Payment: $${downPayment.toLocaleString()} (${downPct}%)`,
                `Loan Amount: $${loanAmount.toLocaleString()}`,
                `Rate: ${rate}% | Term: ${term} years`,
                ``,
                `--- MONTHLY BREAKDOWN ---`,
                `Principal & Interest: $${monthlyPI.toFixed(2)}`,
                `Property Tax: $${monthlyTax.toFixed(2)}`,
                `Insurance: $${monthlyInsurance.toFixed(2)}`,
                hoa > 0 ? `HOA: $${hoa.toFixed(2)}` : null,
                pmi > 0 ? `PMI (< 20% down): $${pmi.toFixed(2)}` : null,
                ``,
                `💰 TOTAL PITI: $${totalPITI.toFixed(2)}/mo`,
                `📊 Total Interest Over Life: $${totalInterest.toLocaleString(undefined, { maximumFractionDigits: 0 })}`,
                ``,
                downPct < 20 ? `⚠️ PMI applies until you reach 20% equity (~$${(price * 0.20).toLocaleString()})` : null,
                `💡 28% Rule: You'd need ~$${Math.round(totalPITI / 0.28 * 12).toLocaleString()}/yr income to qualify.`
            ].filter(Boolean).join('\n');

            return { display: `🏠 **PITI:** $${totalPITI.toFixed(0)}/mo on $${price.toLocaleString()} home`, result };
        }

        case 'rental_yield_analyzer': {
            setStatus('📊 Analyzing rental yield...');
            const price = args.home_price;
            const rent = args.monthly_rent;
            const downPct = args.down_payment_percent || 20;
            const rate = args.interest_rate || 7.0;
            const taxRate = args.annual_tax_rate || 1.1;
            const hoa = args.monthly_hoa || 0;
            const vacancyRate = args.vacancy_rate || 5;
            const maintPct = args.maintenance_percent || 1;

            const downPayment = price * (downPct / 100);
            const loanAmount = price - downPayment;
            const monthlyRate = (rate / 100) / 12;
            const numPayments = 360;

            const monthlyPI = monthlyRate > 0
                ? loanAmount * (monthlyRate * Math.pow(1 + monthlyRate, numPayments)) / (Math.pow(1 + monthlyRate, numPayments) - 1)
                : loanAmount / numPayments;

            const monthlyTax = (price * (taxRate / 100)) / 12;
            const monthlyInsurance = args.monthly_insurance || Math.round(price * 0.004 / 12);
            const monthlyMaint = (price * (maintPct / 100)) / 12;
            const vacancyLoss = rent * (vacancyRate / 100);
            const effectiveRent = rent - vacancyLoss;

            const totalExpenses = monthlyPI + monthlyTax + monthlyInsurance + hoa + monthlyMaint;
            const cashFlow = effectiveRent - totalExpenses;
            const annualCashFlow = cashFlow * 12;

            const grossYield = ((rent * 12) / price * 100).toFixed(2);
            const noi = (effectiveRent * 12) - (monthlyTax * 12) - (monthlyInsurance * 12) - (hoa * 12) - (monthlyMaint * 12);
            const capRate = (noi / price * 100).toFixed(2);
            const cocReturn = downPayment > 0 ? (annualCashFlow / downPayment * 100).toFixed(2) : 'N/A';
            const onePercentRule = rent >= price * 0.01;

            const result = [
                `📊 RENTAL YIELD ANALYSIS`,
                ``,
                `Purchase: $${price.toLocaleString()} | Rent: $${rent.toLocaleString()}/mo`,
                `Down: $${downPayment.toLocaleString()} (${downPct}%) | Rate: ${rate}%`,
                ``,
                `--- MONTHLY CASH FLOW ---`,
                `Effective Rent: $${effectiveRent.toFixed(2)} (${vacancyRate}% vacancy)`,
                `  – Mortgage (P&I): $${monthlyPI.toFixed(2)}`,
                `  – Tax: $${monthlyTax.toFixed(2)}`,
                `  – Insurance: $${monthlyInsurance.toFixed(2)}`,
                hoa > 0 ? `  – HOA: $${hoa.toFixed(2)}` : null,
                `  – Maintenance: $${monthlyMaint.toFixed(2)}`,
                ``,
                `💰 NET CASH FLOW: $${cashFlow.toFixed(2)}/mo ($${annualCashFlow.toFixed(0)}/yr)`,
                ``,
                `--- KEY METRICS ---`,
                `Gross Yield: ${grossYield}%`,
                `Cap Rate: ${capRate}%`,
                `Cash-on-Cash Return: ${cocReturn}%`,
                `1% Rule: ${onePercentRule ? '✅ PASSES' : '❌ FAILS'} (rent/price = ${(rent / price * 100).toFixed(2)}%)`,
                ``,
                parseFloat(capRate) >= 6 ? '🟢 Strong cap rate — solid investment territory' :
                    parseFloat(capRate) >= 4 ? '🟡 Moderate cap rate — market dependent' :
                        '🔴 Low cap rate — likely appreciation play, not cash flow',
                ``,
                `Not financial advice — always verify with local data.`
            ].filter(Boolean).join('\n');

            return { display: `📊 **Cash Flow:** $${cashFlow.toFixed(0)}/mo | Cap: ${capRate}%`, result };
        }

        case 'property_comps': {
            setStatus(`🏘️ Searching comps near ${args.address}...`);
            if (!config.tavilyKey) {
                return {
                    display: `🔑 **Tavily Search Locked**`,
                    result: `Chirp! I need a Tavily API key to search for live comparable sales. Add one in Settings to unlock.\n\nManual alternatives:\n- Zillow.com → Search address → "Nearby Sales"\n- Redfin.com → Search → "Recently Sold"\n- Realtor.com → Property → "Neighborhood" tab`
                };
            }
            try {
                const radius = args.radius_miles || 1;
                const beds = args.beds ? `${args.beds} bed` : '';
                const query = `recently sold homes near ${args.address} within ${radius} miles ${beds} comparable sales price sqft 2025 2026`;
                const res = await fetch('https://api.tavily.com/search', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ api_key: config.tavilyKey, query, search_depth: 'advanced', include_answer: true, include_domains: ['zillow.com', 'redfin.com', 'realtor.com', 'trulia.com'] })
                });
                const data = await res.json();
                playAudioAlert('chirp');
                return {
                    display: `🏘️ **Comparable Sales** near ${args.address}`,
                    result: `${data.answer || 'See results below.'}\n\n${(data.results || []).slice(0, 5).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 10000)
                };
            } catch (err) {
                return { display: `❌ **Comps search failed**`, result: `Error: ${err.message}` };
            }
        }

        case 'neighborhood_score': {
            setStatus(`🏘️ Scouting neighborhood: ${args.address}...`);
            if (!config.tavilyKey) {
                return {
                    display: `🔑 **Tavily Search Locked**`,
                    result: `Chirp! I need a Tavily API key for live neighborhood data.\n\nFree alternatives:\n- GreatSchools.org for school ratings\n- CrimeMapping.com for crime data\n- WalkScore.com for walkability\n- AreaVibes.com for livability scores`
                };
            }
            try {
                const factors = (args.factors || ['schools', 'crime', 'walkability', 'transit', 'amenities', 'growth']).join(', ');
                const query = `${args.address} neighborhood ${factors} ratings score livability review 2025 2026`;
                const res = await fetch('https://api.tavily.com/search', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ api_key: config.tavilyKey, query, search_depth: 'advanced', include_answer: true, include_domains: ['niche.com', 'walkscore.com', 'greatschools.org', 'areavibes.com', 'neighborhoodscout.com'] })
                });
                const data = await res.json();
                playAudioAlert('chirp');
                return {
                    display: `🏘️ **Neighborhood Report:** ${args.address}`,
                    result: `${data.answer || 'See results.'}\n\n${(data.results || []).slice(0, 5).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 10000)
                };
            } catch (err) {
                return { display: `❌ **Neighborhood scan failed**`, result: `Error: ${err.message}` };
            }
        }

        case 'zoning_lookup': {
            setStatus(`📐 Looking up zoning for ${args.address}...`);
            if (!config.tavilyKey) {
                return {
                    display: `🔑 **Tavily Search Locked**`,
                    result: `Chirp! I need a Tavily API key for zoning lookups.\n\nManual options:\n- Search "[your city] zoning map" on Google\n- Check your county assessor's website\n- Look up the parcel on your city's GIS portal`
                };
            }
            try {
                const aduCheck = args.check_adu !== false ? ' ADU accessory dwelling unit eligibility' : '';
                const query = `${args.address} zoning classification residential commercial mixed-use${aduCheck} short-term rental Airbnb rules restrictions 2025 2026`;
                const res = await fetch('https://api.tavily.com/search', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ api_key: config.tavilyKey, query, search_depth: 'advanced', include_answer: true })
                });
                const data = await res.json();
                return {
                    display: `📐 **Zoning Info:** ${args.address}`,
                    result: `${data.answer || 'See results.'}\n\n${(data.results || []).slice(0, 4).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 8000)
                };
            } catch (err) {
                return { display: `❌ **Zoning lookup failed**`, result: `Error: ${err.message}` };
            }
        }

        case 'permit_history_scan': {
            setStatus(`🔍 Scanning permits for ${args.address}...`);
            if (!config.tavilyKey) {
                return {
                    display: `🔑 **Tavily Search Locked**`,
                    result: `Chirp! I need a Tavily API key for permit history.\n\nManual options:\n- Search "[your city] building permit search"\n- Check county assessor records\n- Use BuildZoom.com or HomeAdvisor permit lookup`
                };
            }
            try {
                const years = args.years_back || 10;
                const query = `${args.address} building permits filed renovations inspection history violations last ${years} years public records`;
                const res = await fetch('https://api.tavily.com/search', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ api_key: config.tavilyKey, query, search_depth: 'advanced', include_answer: true })
                });
                const data = await res.json();
                return {
                    display: `🔍 **Permit History:** ${args.address}`,
                    result: `${data.answer || 'See results.'}\n\n${(data.results || []).slice(0, 4).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 8000)
                };
            } catch (err) {
                return { display: `❌ **Permit scan failed**`, result: `Error: ${err.message}` };
            }
        }
    }
}
