from __future__ import annotations

from typing import Any

from us_cpa.tax_years import tax_year_rules


def _as_float(value: Any) -> float:
    if value in (None, ""):
        return 0.0
    return float(value)


def _fact_metadata(facts: dict[str, Any]) -> dict[str, Any]:
    return facts.get("_factMetadata", {})


def _provenance_for(field: str, metadata: dict[str, Any]) -> dict[str, Any]:
    entry = metadata.get(field, {})
    return {"sources": list(entry.get("sources", []))}


def tax_on_ordinary_income(amount: float, filing_status: str, tax_year: int) -> float:
    taxable = max(0.0, amount)
    brackets = tax_year_rules(tax_year)["ordinaryIncomeBrackets"][filing_status]
    lower = 0.0
    tax = 0.0
    for upper, rate in brackets:
        if taxable <= lower:
            break
        portion = min(taxable, upper) - lower
        tax += portion * rate
        lower = upper
    return round(tax, 2)


def resolve_required_forms(normalized: dict[str, Any]) -> list[str]:
    forms = ["f1040"]
    if normalized["income"]["taxableInterest"] > 1500:
        forms.append("f1040sb")
    if normalized["income"]["businessIncome"] != 0:
        forms.extend(["f1040sc", "f1040sse", "f1040s1", "f8995"])
    if normalized["income"]["capitalGainLoss"] != 0:
        forms.extend(["f1040sd", "f8949"])
    if normalized["income"]["rentalIncome"] != 0:
        forms.extend(["f1040se", "f1040s1"])
    if normalized["deductions"]["deductionType"] == "itemized":
        forms.append("f1040sa")
    if normalized["adjustments"]["hsaContribution"] != 0:
        forms.append("f8889")
    if normalized["credits"]["educationCredit"] != 0:
        forms.append("f8863")
    if normalized["credits"]["foreignTaxCredit"] != 0:
        forms.append("f1116")
    if normalized["business"]["qualifiedBusinessIncome"] != 0 and "f8995" not in forms:
        forms.append("f8995")
    if normalized["basis"]["traditionalIraBasis"] != 0:
        forms.append("f8606")
    if normalized["taxes"]["additionalMedicareTax"] != 0:
        forms.append("f8959")
    if normalized["taxes"]["netInvestmentIncomeTax"] != 0:
        forms.append("f8960")
    if normalized["taxes"]["alternativeMinimumTax"] != 0:
        forms.append("f6251")
    if normalized["taxes"]["additionalTaxPenalty"] != 0:
        forms.append("f5329")
    if normalized["credits"]["energyCredit"] != 0:
        forms.append("f5695")
    if normalized["depreciation"]["depreciationExpense"] != 0:
        forms.append("f4562")
    if normalized["assetSales"]["section1231GainLoss"] != 0:
        forms.append("f4797")
    return list(dict.fromkeys(forms))


def normalize_case_facts(facts: dict[str, Any], tax_year: int) -> dict[str, Any]:
    rules = tax_year_rules(tax_year)
    metadata = _fact_metadata(facts)
    filing_status = facts.get("filingStatus", "single")
    wages = _as_float(facts.get("wages"))
    interest = _as_float(facts.get("taxableInterest"))
    business_income = _as_float(facts.get("businessIncome"))
    capital_gain_loss = _as_float(facts.get("capitalGainLoss"))
    rental_income = _as_float(facts.get("rentalIncome"))
    withholding = _as_float(facts.get("federalWithholding"))
    itemized_deductions = _as_float(facts.get("itemizedDeductions"))
    hsa_contribution = _as_float(facts.get("hsaContribution"))
    education_credit = _as_float(facts.get("educationCredit"))
    foreign_tax_credit = _as_float(facts.get("foreignTaxCredit"))
    qualified_business_income = _as_float(facts.get("qualifiedBusinessIncome"))
    traditional_ira_basis = _as_float(facts.get("traditionalIraBasis"))
    additional_medicare_tax = _as_float(facts.get("additionalMedicareTax"))
    net_investment_income_tax = _as_float(facts.get("netInvestmentIncomeTax"))
    alternative_minimum_tax = _as_float(facts.get("alternativeMinimumTax"))
    additional_tax_penalty = _as_float(facts.get("additionalTaxPenalty"))
    energy_credit = _as_float(facts.get("energyCredit"))
    depreciation_expense = _as_float(facts.get("depreciationExpense"))
    section1231_gain_loss = _as_float(facts.get("section1231GainLoss"))

    adjusted_gross_income = wages + interest + business_income + capital_gain_loss + rental_income
    standard_deduction = rules["standardDeduction"][filing_status]
    deduction_type = "itemized" if itemized_deductions > standard_deduction else "standard"
    deduction_amount = itemized_deductions if deduction_type == "itemized" else standard_deduction
    taxable_income = max(0.0, adjusted_gross_income - deduction_amount)
    income_tax = tax_on_ordinary_income(taxable_income, filing_status, tax_year)
    self_employment_tax = round(max(0.0, business_income) * 0.9235 * 0.153, 2)
    total_tax = round(
        income_tax
        + self_employment_tax
        + additional_medicare_tax
        + net_investment_income_tax
        + alternative_minimum_tax
        + additional_tax_penalty,
        2,
    )
    total_payments = withholding
    total_credits = round(education_credit + foreign_tax_credit + energy_credit, 2)
    refund = round(max(0.0, total_payments + total_credits - total_tax), 2)
    balance_due = round(max(0.0, total_tax - total_payments - total_credits), 2)

    normalized = {
        "taxYear": tax_year,
        "taxpayer": {
            "fullName": facts.get("taxpayer.fullName", "Unknown Taxpayer"),
        },
        "spouse": {
            "fullName": facts.get("spouse.fullName", ""),
        },
        "dependents": list(facts.get("dependents", [])),
        "filingStatus": filing_status,
        "income": {
            "wages": wages,
            "taxableInterest": interest,
            "businessIncome": business_income,
            "capitalGainLoss": capital_gain_loss,
            "rentalIncome": rental_income,
        },
        "adjustments": {
            "hsaContribution": hsa_contribution,
        },
        "payments": {
            "federalWithholding": withholding,
        },
        "deductions": {
            "standardDeduction": standard_deduction,
            "itemizedDeductions": itemized_deductions,
            "deductionType": deduction_type,
            "deductionAmount": deduction_amount,
        },
        "credits": {
            "educationCredit": education_credit,
            "foreignTaxCredit": foreign_tax_credit,
            "energyCredit": energy_credit,
        },
        "taxes": {
            "incomeTax": income_tax,
            "selfEmploymentTax": self_employment_tax,
            "additionalMedicareTax": additional_medicare_tax,
            "netInvestmentIncomeTax": net_investment_income_tax,
            "alternativeMinimumTax": alternative_minimum_tax,
            "additionalTaxPenalty": additional_tax_penalty,
            "totalTax": total_tax,
        },
        "business": {
            "qualifiedBusinessIncome": qualified_business_income,
        },
        "basis": {
            "traditionalIraBasis": traditional_ira_basis,
        },
        "depreciation": {
            "depreciationExpense": depreciation_expense,
        },
        "assetSales": {
            "section1231GainLoss": section1231_gain_loss,
        },
        "totals": {
            "adjustedGrossIncome": round(adjusted_gross_income, 2),
            "taxableIncome": round(taxable_income, 2),
            "totalPayments": round(total_payments, 2),
            "totalCredits": total_credits,
            "refund": refund,
            "balanceDue": balance_due,
        },
        "provenance": {
            "income.wages": _provenance_for("wages", metadata),
            "income.taxableInterest": _provenance_for("taxableInterest", metadata),
            "income.businessIncome": _provenance_for("businessIncome", metadata),
            "income.capitalGainLoss": _provenance_for("capitalGainLoss", metadata),
            "income.rentalIncome": _provenance_for("rentalIncome", metadata),
            "payments.federalWithholding": _provenance_for("federalWithholding", metadata),
        },
    }
    normalized["requiredForms"] = resolve_required_forms(normalized)
    return normalized
