"""Tax reporting routes."""

from fastapi import APIRouter, HTTPException, Response
from pydantic import BaseModel, EmailStr
from typing import Optional, List
from datetime import datetime
from agenticlypay.tax import TaxReporter
from agenticlypay.utils.firestore_storage import FirestoreStorage

router = APIRouter()
tax_reporter = TaxReporter()
storage = FirestoreStorage()


class Generate1099Request(BaseModel):
    """Request model for generating a 1099 form."""

    developer_account_id: str
    year: int


class GenerateAll1099Request(BaseModel):
    """Request model for generating 1099 forms for all developers."""

    year: int
    developer_account_ids: Optional[List[str]] = None


class ConsentRequest(BaseModel):
    """Request model for electronic delivery consent."""

    email: EmailStr
    consented: bool
    method: str = "console"  # "console" or "email_link"


class TaxInfoRequest(BaseModel):
    """Request model for tax information."""

    email: EmailStr
    name: str
    ssn: Optional[str] = None
    ein: Optional[str] = None
    address: dict


@router.get("/earnings/{account_id}/{year}")
async def get_annual_earnings(account_id: str, year: int):
    """Get annual earnings for a developer."""
    try:
        earnings = tax_reporter.calculate_annual_earnings(account_id, year)
        return {"success": True, "earnings": earnings}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/1099/generate")
async def generate_1099(request: Generate1099Request):
    """Generate a 1099 form for a developer."""
    try:
        result = tax_reporter.generate_1099_form(
            developer_account_id=request.developer_account_id, year=request.year
        )
        return {"success": result["success"], "form": result}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/1099/generate-all")
async def generate_all_1099(request: GenerateAll1099Request):
    """Generate 1099 forms for all eligible developers."""
    try:
        results = tax_reporter.generate_all_1099_forms(
            year=request.year, developer_account_ids=request.developer_account_ids
        )
        return {"success": True, "results": results}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/forms/{account_id}")
async def get_tax_forms(account_id: str, year: Optional[int] = None):
    """Get tax forms for a developer."""
    try:
        forms = tax_reporter.get_tax_forms(account_id, year=year)
        return {"success": True, "forms": forms}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/1099/consent")
async def set_1099_consent(request: ConsentRequest):
    """Record electronic delivery consent for 1099 forms."""
    try:
        storage.set_1099_consent(
            email=request.email,
            consented=request.consented,
            consent_date=datetime.now(),
            method=request.method,
        )
        return {"success": True, "message": "Consent recorded"}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/1099/withdraw-consent")
async def withdraw_1099_consent(email: EmailStr):
    """Withdraw electronic delivery consent for 1099 forms."""
    try:
        storage.withdraw_1099_consent(email)
        return {"success": True, "message": "Consent withdrawn"}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/1099/consent-status")
async def get_consent_status(email: EmailStr):
    """Get 1099 electronic delivery consent status."""
    try:
        consent = storage.get_1099_consent(email)
        if consent:
            return {"success": True, "consent": consent}
        else:
            return {"success": True, "consent": None, "consented": False}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/1099/send")
async def send_1099(request: Generate1099Request):
    """Generate and send 1099 form via email."""
    try:
        result = tax_reporter.generate_and_send_1099(
            developer_account_id=request.developer_account_id, year=request.year
        )
        return {"success": result["success"], "form": result}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/1099/download/{form_id}")
async def download_1099(form_id: str):
    """Download 1099 PDF by form ID."""
    try:
        from google.cloud import firestore
        from agenticlypay.config import config
        
        db = firestore.Client(project=config.project_id or "agenticlypay-com")
        form_doc = db.collection("1099_forms").document(form_id).get()
        
        if not form_doc.exists:
            raise HTTPException(status_code=404, detail="Form not found")
        
        form_data = form_doc.to_dict()
        pdf_bytes = tax_reporter.generate_1099_pdf(
            email=form_data["email"],
            developer_account_id=form_data["developer_account_id"],
            year=form_data["year"],
            amount_cents=form_data["amount_cents"],
        )
        
        return Response(
            content=pdf_bytes,
            media_type="application/pdf",
            headers={"Content-Disposition": f'attachment; filename="1099-MISC-{form_data["year"]}-{form_id}.pdf"'},
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/tax-info")
async def store_tax_info(request: TaxInfoRequest):
    """Store tax information for a developer."""
    try:
        storage.store_tax_info(
            email=request.email,
            tax_info={
                "name": request.name,
                "ssn": request.ssn,
                "ein": request.ein,
                "address": request.address,
            },
        )
        return {"success": True, "message": "Tax information stored"}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/tax-info")
async def get_tax_info(email: EmailStr):
    """Get tax information for a developer."""
    try:
        tax_info = storage.get_tax_info(email)
        if tax_info:
            return {"success": True, "tax_info": tax_info}
        else:
            return {"success": True, "tax_info": None}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

