"""
Formatters for DataDocked API responses
Provides human-readable output for vessel data
"""

from typing import Optional


def format_vessel_location(vessel: dict) -> str:
    """Format vessel location data"""
    return f"""
**{vessel.get('name', 'Unknown')}** (IMO: {vessel.get('imo', 'N/A')}, MMSI: {vessel.get('mmsi', 'N/A')})

| Field | Value |
|-------|-------|
| Position | {vessel.get('latitude', 0):.4f}°N, {vessel.get('longitude', 0):.4f}°E |
| Speed | {vessel.get('speed', 0)} knots |
| Course | {vessel.get('course', 0)}° |
| Heading | {vessel.get('heading', 0)}° |
| Destination | {vessel.get('destination') or 'Not reported'} |
| ETA | {vessel.get('eta') or 'Not available'} |
| Status | {vessel.get('nav_status', 'Unknown')} |
| Last Update | {vessel.get('timestamp', 'Unknown')} |
""".strip()


def format_vessel_details(vessel: dict) -> str:
    """Format vessel details"""
    return f"""
**{vessel.get('name', 'Unknown')}** (IMO: {vessel.get('imo', 'N/A')})

| Field | Value |
|-------|-------|
| Type | {vessel.get('type', 'Unknown')} |
| Flag | {vessel.get('flag', 'Unknown')} |
| Built | {vessel.get('built', 'Unknown')} |
| Call Sign | {vessel.get('call_sign', 'N/A')} |
| Gross Tonnage | {vessel.get('gross_tonnage', 0):,} GT |
| Deadweight | {vessel.get('deadweight', 0):,} DWT |
| Length | {vessel.get('length', 0)} m |
| Beam | {vessel.get('beam', 0)} m |
| Draft | {vessel.get('draft', 0)} m |
""".strip()


def format_vessel_particulars(particulars: dict) -> str:
    """Format vessel particulars"""
    result = f"""
**Vessel Particulars** (IMO: {particulars.get('imo', 'N/A')})

| Dimension | Value |
|-----------|-------|
| Length Overall | {particulars.get('length_overall', 0)} m |
| Beam | {particulars.get('beam', 0)} m |
| Depth | {particulars.get('depth', 0)} m |
| Draft | {particulars.get('draft', 0)} m |
| Gross Tonnage | {particulars.get('gross_tonnage', 0):,} GT |
| Net Tonnage | {particulars.get('net_tonnage', 0):,} NT |
| Deadweight | {particulars.get('deadweight', 0):,} DWT |
""".strip()

    if particulars.get('teu_capacity'):
        result += f"\n| TEU Capacity | {particulars['teu_capacity']:,} TEU |"

    return result


def format_engine_data(engine: dict) -> str:
    """Format engine data"""
    return f"""
**Engine Data** (IMO: {engine.get('imo', 'N/A')})

| Specification | Value |
|---------------|-------|
| Main Engine | {engine.get('main_engine_type', 'Unknown')} |
| Power | {engine.get('main_engine_power', 0):,} kW |
| Fuel Type | {engine.get('fuel_type', 'Unknown')} |
| Service Speed | {engine.get('speed_service', 0)} knots |
| Max Speed | {engine.get('speed_max', 0)} knots |
""".strip()


def format_management_data(mgmt: dict) -> str:
    """Format management data"""
    return f"""
**Management** (IMO: {mgmt.get('imo', 'N/A')})

| Role | Entity |
|------|--------|
| Owner | {mgmt.get('owner', 'Unknown')} |
| Operator | {mgmt.get('operator', 'Unknown')} |
| Manager | {mgmt.get('manager', 'Unknown')} |
| P&I Club | {mgmt.get('p_and_i_club', 'Unknown')} |
| Class Society | {mgmt.get('class_society', 'Unknown')} |
""".strip()


def format_port_calls(port_calls: list) -> str:
    """Format port call history"""
    if not port_calls:
        return "No port call history available."

    result = "**Port Call History**\n\n"
    result += "| Port | Country | Arrival | Departure | Duration |\n"
    result += "|------|---------|---------|-----------|----------|\n"

    for call in port_calls[:20]:
        result += f"| {call.get('port_name', 'Unknown')} ({call.get('port_code', 'N/A')}) | {call.get('country', 'N/A')} | {call.get('arrival', 'N/A')} | {call.get('departure', 'N/A')} | {call.get('time_in_port_hours', 0):.1f} hrs |\n"

    if len(port_calls) > 20:
        result += f"\n*...and {len(port_calls) - 20} more port calls*"

    return result.strip()


def format_port_traffic(traffic: dict) -> str:
    """Format port traffic"""
    result = f"**Port Traffic: {traffic.get('port_code', 'Unknown')}**\n\n"

    arrivals = traffic.get('arrivals', [])
    result += f"### Arrivals ({len(arrivals)})\n"
    if arrivals:
        result += "| Vessel | Position | Speed | Destination |\n"
        result += "|--------|----------|-------|-------------|\n"
        for v in arrivals[:10]:
            result += f"| {v.get('name', 'Unknown')} | {v.get('latitude', 0):.2f}°N, {v.get('longitude', 0):.2f}°E | {v.get('speed', 0)} kts | {v.get('destination') or 'N/A'} |\n"
    else:
        result += "No arrivals recorded.\n"

    departures = traffic.get('departures', [])
    result += f"\n### Departures ({len(departures)})\n"
    if departures:
        result += "| Vessel | Position | Speed | Destination |\n"
        result += "|--------|----------|-------|-------------|\n"
        for v in departures[:10]:
            result += f"| {v.get('name', 'Unknown')} | {v.get('latitude', 0):.2f}°N, {v.get('longitude', 0):.2f}°E | {v.get('speed', 0)} kts | {v.get('destination') or 'N/A'} |\n"
    else:
        result += "No departures recorded.\n"

    expected = traffic.get('expected', [])
    result += f"\n### Expected ({len(expected)})\n"
    if expected:
        result += "| Vessel | ETA | Destination |\n"
        result += "|--------|-----|-------------|\n"
        for v in expected[:10]:
            result += f"| {v.get('name', 'Unknown')} | {v.get('eta') or 'Unknown'} | {v.get('destination') or 'N/A'} |\n"
    else:
        result += "No expected arrivals.\n"

    return result.strip()


def format_psc_inspections(inspections: list) -> str:
    """Format PSC inspection history"""
    if not inspections:
        return "No PSC inspection records found."

    result = "**Port State Control Inspections**\n\n"
    result += "| Date | Port | Country | Deficiencies | Detained |\n"
    result += "|------|------|---------|--------------|----------|\n"

    detentions = sum(1 for i in inspections if i.get('detained'))
    total_deficiencies = sum(i.get('deficiencies', 0) for i in inspections)

    for insp in inspections:
        detained_str = f"Yes ({insp.get('detention_days', 0)} days)" if insp.get('detained') else "No"
        result += f"| {insp.get('date', 'N/A')} | {insp.get('port', 'N/A')} | {insp.get('country', 'N/A')} | {insp.get('deficiencies', 0)} | {detained_str} |\n"

    result += f"\n**Summary:** {len(inspections)} inspections, {total_deficiencies} total deficiencies, {detentions} detention(s)"

    return result.strip()


def format_weather(weather: dict) -> str:
    """Format weather data"""
    return f"""
**Weather Conditions** ({weather.get('latitude', 0):.2f}°N, {weather.get('longitude', 0):.2f}°E)

| Condition | Value |
|-----------|-------|
| Temperature | {weather.get('temperature_c', 0)}°C |
| Wind | {weather.get('wind_speed_kts', 0)} kts from {weather.get('wind_direction', 0)}° |
| Wave Height | {weather.get('wave_height_m', 0)} m |
| Visibility | {weather.get('visibility_nm', 0)} nm |
| Conditions | {weather.get('conditions', 'Unknown')} |
""".strip()


def format_historical_positions(positions: list) -> str:
    """Format historical positions"""
    if not positions:
        return "No historical position data available."

    result = f"**Historical Positions** ({len(positions)} records)\n\n"
    result += "| Timestamp | Position | Speed | Course |\n"
    result += "|-----------|----------|-------|--------|\n"

    # Show first 20 and last 5 if many records
    if len(positions) <= 25:
        show_positions = positions
    else:
        show_positions = positions[:20] + positions[-5:]

    shown = 0
    for i, pos in enumerate(show_positions):
        if len(positions) > 25 and i == 20 and shown == 20:
            result += f"| ... | *{len(positions) - 25} more records* | ... | ... |\n"
        result += f"| {pos.get('timestamp', 'N/A')} | {pos.get('latitude', 0):.4f}°N, {pos.get('longitude', 0):.4f}°E | {pos.get('speed', 0)} kts | {pos.get('course', 0)}° |\n"
        shown += 1

    return result.strip()


def format_credit_estimate(operation: str, cost: int, balance: Optional[int] = None) -> str:
    """Format credit estimate warning"""
    result = "```\n"
    result += "--- Credit Estimate ---\n"
    result += f"Operation: {operation}\n"
    result += f"Estimated Cost: {cost} credit{'s' if cost != 1 else ''}\n"
    if balance is not None:
        result += f"Current Balance: {balance} credits\n"
    result += "To disable: set DATADOCKED_SHOW_COST=false\n"
    result += "------------------------\n"
    result += "```\n"
    return result


def format_credits_used(used: int, remaining: Optional[int] = None) -> str:
    """Format credits used footer"""
    result = f"\n*Credits used: {used}"
    if remaining is not None:
        result += f" | Remaining: {remaining}"
    result += "*"
    return result
