"""Verktøylista og dispatchen som MCP-serveren deler mellom stdio (mcp_server.py) og HTTP (/mcp i app.py).
Alle verktøy kaller API-et under /v1 gjennom `kall(metode, sti, params, kropp)` som den som bruker modulen gir."""

VERSJON = "1.3"
# Beskrivelsene er på engelsk fordi det er språket agenter søker, velger verktøy og resonnerer på. Navn på verktøy og felt er norske og
# uendret (de er API-et); beskrivelsene forklarer dem. Verdier som "ja"/"nei" og status "ikke_funnet" er også uendret.
JN = {"type": "string", "enum": ["ja", "nei"], "description": "ja = yes, nei = no"}
FILTER = {"bransje": {"type": "string", "description": "Industry: NACE code prefix, several separated by comma, e.g. 69.2,85.1. Use the tool bransjer to list codes."},
          "fylke": {"type": "string", "description": "County (fylke), several separated by comma, e.g. Oslo,Rogaland"}, "kommune": {"type": "string", "description": "Municipality name"},
          "kundetype": {"type": "string", "enum": ["B2B", "B2C", "begge", "offentlig"], "description": "Who the company sells to (begge = both, offentlig = public sector)"},
          "ansatte_min": {"type": "number", "description": "Minimum employees"}, "ansatte_maks": {"type": "number", "description": "Maximum employees"},
          "omsetning_min": {"type": "number", "description": "Minimum latest annual revenue in NOK"}, "omsetning_maks": {"type": "number", "description": "Maximum latest annual revenue in NOK"},
          "stiftet_min": {"type": "integer", "description": "Founded in or after this year"}, "stiftet_maks": {"type": "integer", "description": "Founded in or before this year"},
          "utestaende_min": {"type": "number", "description": "Minimum estimated accounts receivable in NOK"}, "kunder_min": {"type": "number", "description": "Minimum estimated number of customers"},
          "fakturaer_min": {"type": "number", "description": "Minimum estimated invoices per year"},
          "kan_sms": {**JN, "description": "Company has a mobile number that can receive SMS (ja/nei)"}, "har_dl_mobil": {**JN, "description": "Managing director has a direct mobile number (ja/nei)"},
          "har_dl_epost": {**JN, "description": "Managing director has a direct e-mail (ja/nei)"}, "har_dl_linkedin": {**JN, "description": "Managing director has a LinkedIn profile (ja/nei)"},
          "har_nettside": {**JN, "description": "Company has a website (ja/nei)"}, "har_regnskap": {**JN, "description": "Annual accounts are available (ja/nei)"},
          "fakturerer_mange": {**JN, "description": "Website mentions reminder fees, debt collection, direct debit or e-invoice, i.e. the company invoices many customers (ja/nei)"},
          "kjede": {**JN, "description": "Part of a chain (ja/nei)"}, "konsern": {**JN, "description": "Part of a corporate group (ja/nei)"},
          "signal": {"type": "string", "description": "Invoicing signal found on the website: purregebyr, inkasso, avtalegiro, efaktura, abonnement, ehf …"},
          "regnskapsforer": {"type": "string", "description": "Accountant name (substring)"}, "revisor": {"type": "string", "description": "Auditor name (substring)"},
          "sorter": {"type": "string", "enum": ["omsetning", "ansatte", "utestaende", "kunder", "fakturaer", "nyeste", "navn"],
                     "description": "Sort by revenue, employees, receivables, customers, invoices, newest or name"},
          "antall": {"type": "integer", "description": "Hits per page, up to 100"}, "side": {"type": "integer", "description": "Page number, from 1"},
          "antall_kun": {"type": "string", "enum": ["ja"], "description": "Only count the hits. Free, does not use quota. Use it before a large search."},
          "status": {"type": "string", "enum": ["aktiv", "konkurs", "avvikling", "tvangsavvikling", "alle"],
                     "description": "Default aktiv (active). konkurs = bankrupt, avvikling = winding up, tvangsavvikling = forced dissolution, alle = all."},
          "register": {"type": "string", "enum": ["ja"], "description": "Search the whole Norwegian business register (1.2 million entities; name, org number, place, industry, legal form only) "
                                                                         "instead of the enriched dataset. Use it to find the org number of small companies and sole proprietorships."}}
LES = {"readOnlyHint": True, "openWorldHint": False}

VERKTOY = [
    {"name": "sok_selskaper", "title": "Search Norwegian companies", "annotations": LES,
     "description": "Search Norwegian companies (all active AS, ASA, ANS, DA, SA etc., also without employees; filter on employees for operating companies). "
                    "Free text (company name, org number, managing director) plus filters on industry, location, size, founding year, customer type, estimated receivables/customers/invoices, "
                    "invoicing signals and whether the managing director has a direct mobile, e-mail or LinkedIn. Each hit returned counts as one search hit (søketreff); antall_kun=ja is free.",
     "inputSchema": {"type": "object", "properties": {"q": {"type": "string", "description": "Free text or 9-digit org number (orgnr)"}, **FILTER}}},
    {"name": "berik_selskap", "title": "Enrich one Norwegian company", "annotations": LES,
     "description": "Everything about one Norwegian company by org number (orgnr): register data, latest annual accounts, roles, group/chain, estimates of receivables/customers/invoices, "
                    "invoicing signals, and the managing director's (daglig leder) best e-mail and LinkedIn with source and confidence grade A–E. The mobile number shows as «tilgjengelig» "
                    "(available) until you call finn_mobil. Costs 1 enrichment (berikelse) when coverage is full (dekning: full). Companies outside the enriched dataset return register data "
                    "for free (dekning: register).",
     "inputSchema": {"type": "object", "properties": {"orgnr": {"type": "string", "description": "9-digit Norwegian organisation number"}}, "required": ["orgnr"]}},
    {"name": "berik_selskaper", "title": "Enrich up to 100 companies", "annotations": LES,
     "description": "Same as berik_selskap for up to 100 org numbers in one call. One enrichment per company found; unknown org numbers cost nothing.",
     "inputSchema": {"type": "object", "properties": {"orgnrs": {"type": "array", "items": {"type": "string"}, "maxItems": 100, "description": "9-digit org numbers"}}, "required": ["orgnrs"]}},
    {"name": "sok_personer", "title": "Search managing directors", "annotations": LES,
     "description": "Search managing directors (daglig leder, the Norwegian CEO role) of Norwegian companies by name, with the same filters as the company search. Counts search hits.",
     "inputSchema": {"type": "object", "properties": {"q": {"type": "string", "description": "Person name"}, **FILTER}}},
    {"name": "berik_person", "title": "Enrich a managing director", "annotations": LES,
     "description": "Best e-mail, LinkedIn and other companies of a managing director. Give orgnr, or the name (navn) plus company (firma) or domain (domene). 1 enrichment when the person is found.",
     "inputSchema": {"type": "object", "properties": {"orgnr": {"type": "string", "description": "9-digit org number"}, "navn": {"type": "string", "description": "Full name"},
                                                      "firma": {"type": "string", "description": "Company name"}, "domene": {"type": "string", "description": "Company domain, e.g. firma.no"}}}},
    {"name": "finn_mobil", "title": "Find the managing director's mobile number", "annotations": LES,
     "description": "Direct mobile number of the managing director with source and confidence grade. Costs 1 phone credit (telefonpoeng, NOK 1.50) when a number is delivered, nothing otherwise. "
                    "Ask the user before fetching many.",
     "inputSchema": {"type": "object", "properties": {"orgnr": {"type": "string", "description": "9-digit org number"}, "firma": {"type": "string", "description": "Company name"},
                                                      "domene": {"type": "string", "description": "Company domain"}}}},
    {"name": "finn_epost", "title": "Find an e-mail address", "annotations": LES,
     "description": "E-mail address for a named person at a Norwegian company domain: the known address if we have it, otherwise the domain's confirmed pattern, with confidence and alternatives. 1 enrichment.",
     "inputSchema": {"type": "object", "properties": {"fornavn": {"type": "string", "description": "First name"}, "etternavn": {"type": "string", "description": "Last name"},
                                                      "domene": {"type": "string", "description": "Domain, e.g. firma.no"}, "orgnr": {"type": "string", "description": "Org number, instead of domain"}},
                     "required": ["fornavn", "etternavn"]}},
    {"name": "valider_epost", "title": "Validate e-mail addresses", "annotations": LES,
     "description": "Validate up to 100 e-mail addresses: syntax, domain answers (MX), role address, disposable domain, known in the dataset. 1 enrichment per address.",
     "inputSchema": {"type": "object", "properties": {"eposter": {"type": "array", "items": {"type": "string"}, "maxItems": 100, "description": "E-mail addresses"}}, "required": ["eposter"]}},
    {"name": "omvendt_epost", "title": "Reverse e-mail or domain lookup", "annotations": LES,
     "description": "Which Norwegian company and which manager an e-mail address or a domain belongs to. 1 enrichment on a hit.",
     "inputSchema": {"type": "object", "properties": {"epost": {"type": "string", "description": "E-mail address"}, "domene": {"type": "string", "description": "Domain"}}}},
    {"name": "sjekk_liste", "title": "Check your own contact list", "annotations": {"readOnlyHint": False, "destructiveHint": False, "openWorldHint": False},
     "description": "Check the user's own contacts or customers against Firmasett: up to 100 rows with orgnr/firma/domene, navn, epost and telefon. Answers per row whether the company and the person "
                    "exist, whether e-mail and phone match what we have (lik = same, avviker = differs, vi_mangler = we lack it, du_mangler = you lack it) and gives the best e-mail. "
                    "1 enrichment per matched row. Use it to clean a CRM or fill gaps. Rows sent in are stored and used to improve the dataset (terms § 6).",
     "inputSchema": {"type": "object", "properties": {"rader": {"type": "array", "maxItems": 100, "description": "Rows to check", "items": {"type": "object", "properties": {
         "orgnr": {"type": "string"}, "firma": {"type": "string", "description": "Company name"}, "domene": {"type": "string", "description": "Domain"}, "navn": {"type": "string", "description": "Person name"},
         "epost": {"type": "string"}, "telefon": {"type": "string"}, "linkedin": {"type": "string"}, "tittel": {"type": "string", "description": "Job title"},
         "id": {"type": "string", "description": "Your own id, returned unchanged"}}}}}, "required": ["rader"]}},
    {"name": "bransjer", "title": "List industries and counties", "annotations": LES,
     "description": "List of industry codes (NACE, 2 digits) with number of companies and coverage of the managing director's e-mail and mobile, plus the counties. Free.",
     "inputSchema": {"type": "object", "properties": {}}},
    {"name": "konto", "title": "Account and quota", "annotations": LES,
     "description": "Plan, quotas, usage in the current window and phone credits for the key. Free, does not use quota.",
     "inputSchema": {"type": "object", "properties": {}}},
    {"name": "bruk", "title": "Usage per day", "annotations": LES,
     "description": "Usage per day for the last 30 days. Free.",
     "inputSchema": {"type": "object", "properties": {}}},
    {"name": "betalingslenke", "title": "Get a payment link to upgrade", "annotations": {"readOnlyHint": False, "destructiveHint": False, "openWorldHint": True},
     "description": "Create a card payment link for the user: a paid plan (plan: solo, pro or team; monthly, cancel any time) or a phone credit pack (telefonpoeng: 180, 650 or 1300; "
                    "needs a paid plan). Give the link to the user; they pay in the browser and the plan or credits are active within seconds. Use it when the quota is used up "
                    "(error kvote_brukt) or mobile numbers are needed (error ingen_telefonpoeng), after asking the user. Free.",
     "inputSchema": {"type": "object", "properties": {"plan": {"type": "string", "enum": ["solo", "pro", "team"]}, "telefonpoeng": {"type": "integer", "enum": [180, 650, 1300]}}}},
    {"name": "onboarding", "title": "Onboarding status", "annotations": LES,
     "description": "Onboarding status for the user: what is stored and which questions remain. Free. Call it first in a new conversation if the server instructions say onboarding is not complete.",
     "inputSchema": {"type": "object", "properties": {}}},
    {"name": "lagre_profil", "title": "Save onboarding answers", "annotations": {"readOnlyHint": False, "destructiveHint": False, "idempotentHint": True, "openWorldHint": False},
     "description": "Save the onboarding answers on the account: full name, mobile number, work e-mail, company, what the user decides on and what the user influences decisions on. "
                    "Can be called several times with partial answers. Free.",
     "inputSchema": {"type": "object", "properties": {"navn": {"type": "string", "description": "Full name"}, "telefon": {"type": "string", "description": "Mobile number"},
                                                      "epost": {"type": "string", "description": "Work e-mail"}, "firma": {"type": "string", "description": "Company name or org number"},
                                                      "bestemmer": {"type": "string", "description": "What the user decides on (responsibility, budget, purchasing)"},
                                                      "paavirker": {"type": "string", "description": "What the user influences decisions on without deciding alone"}}}},
]
ONBOARDING_SPORSMAL = [("navn", "Hva er fullt navn ditt?"), ("telefon", "Hvilket mobilnummer kan vi nå deg på?"), ("epost", "Hvilken jobb-e-post bruker du?"),
                       ("firma", "Hvilket firma jobber du i (navn eller orgnr)?"), ("bestemmer", "Hva bestemmer du over i jobben din (ansvar, budsjett, innkjøp)?"),
                       ("paavirker", "Hva påvirker du beslutninger om, uten å bestemme selv?")]
ONBOARDING_EN = {"navn": "What is your full name?", "telefon": "Which mobile number can we reach you on?", "epost": "Which work e-mail do you use?",
                 "firma": "Which company do you work for (name or org number)?", "bestemmer": "What do you decide on in your job (responsibility, budget, purchasing)?",
                 "paavirker": "What do you influence decisions on, without deciding alone?"}
INSTRUKSJONER = ("Firmasett is Norwegian B2B company data, rebuilt every night: 450 000 Norwegian companies fully enriched (latest annual accounts, the managing director (daglig leder) with "
                 "best e-mail, mobile and LinkedIn, each with source and confidence grade A–E), plus the whole Norwegian business register for lookups by org number (register data only). "
                 "Tool and field names are Norwegian: orgnr = organisation number, daglig_leder = managing director, omsetning = revenue, ansatte = employees, fylke = county, "
                 "berikelse = enrichment, sok = search hits, telefonpoeng = phone credits. Every answer has status ok | ikke_funnet (not found) | feil (error) and meta with remaining quota; "
                 "ikke_funnet costs nothing. Mobile numbers cost phone credits (telefonpoeng, NOK 1.50 each): ask the user before fetching many. When the quota is used up or phone credits are missing, offer the user an upgrade with betalingslenke. Run sok_selskaper with antall_kun=ja before large searches. "
                 "Report source and grade when you give contact details. Norwegian law: calling a managing director at work and e-mailing a role in a business is allowed; SMS to a private "
                 "person's mobile needs consent (markedsføringsloven § 15). Answer in the user's language.")


def uten_nokkel_instruks(basis):
    """Instruksjonene en klient uten nøkkel får: hva serveren er og hvordan den logger inn. Verktøykall gir 401 til det er gjort."""
    return (" NOT SIGNED IN: you can list the tools, but calling them needs authentication. Either sign in with OAuth (the server answers 401 with a resource_metadata pointer), "
            f"or create a free key with POST {basis}/v1/registrer {{\"epost\": \"<the user's own e-mail>\"}} and reconnect with the header Authorization: Bearer fs_… "
            f"A human can also create the key at {basis}/konsoll. Free plan: 1 000 enrichments and 100 search hits, no card.")


def utfor(navn, a, kall):
    """Kjører ett verktøy mot API-et gjennom kall(metode, sti, params, kropp)."""
    a = a or {}
    if navn == "sok_selskaper":
        return kall("GET", "/v1/selskaper/sok", a, None)
    if navn == "berik_selskap":
        return kall("GET", f"/v1/selskaper/{a.get('orgnr', '')}", None, None)
    if navn == "berik_selskaper":
        return kall("POST", "/v1/selskaper/berik", None, a)
    if navn == "sok_personer":
        return kall("GET", "/v1/personer/sok", a, None)
    if navn == "berik_person":
        return kall("POST", "/v1/berik/person", None, a)
    if navn == "finn_mobil":
        return kall("POST", "/v1/telefon/finn", None, a)
    if navn == "finn_epost":
        return kall("POST", "/v1/epost/finn", None, a)
    if navn == "valider_epost":
        return kall("POST", "/v1/epost/valider", None, a)
    if navn == "omvendt_epost":
        return kall("GET", "/v1/epost/omvendt", a, None)
    if navn == "sjekk_liste":
        return kall("POST", "/v1/sjekk", None, a)
    if navn == "bransjer":
        return kall("GET", "/v1/bransjer", None, None)
    if navn == "konto":
        return kall("GET", "/v1/konto", None, None)
    if navn == "bruk":
        return kall("GET", "/v1/bruk", None, None)
    if navn == "betalingslenke":
        return kall("POST", "/v1/betaling", None, a)
    if navn == "onboarding":
        return kall("GET", "/v1/onboarding", None, None)
    if navn == "lagre_profil":
        return kall("POST", "/v1/onboarding", None, a)
    return {"status": "feil", "feil": {"kode": "ukjent_verktoy", "melding": f"Ukjent verktøy {navn}"}}


def onboarding_instruks(status):
    """Tillegg til instruksjonene når brukeren ikke har fullført onboardingen (fra GET /v1/onboarding)."""
    if not status or status.get("status") != "ok" or status["resultat"].get("fullfort"):
        return ""
    mangler = status["resultat"].get("mangler", [])
    sp = [ONBOARDING_EN[f] for f, _ in ONBOARDING_SPORSMAL if f in mangler]
    return (" ONBOARDING NOT COMPLETE: before you do lookups for the user, ask these questions in the user's language, one or two at a time, and save the answers with lagre_profil: "
            + " ".join(f"({i + 1}) {q}" for i, q in enumerate(sp)) + " Explain briefly that the answers are used to tailor the service and to reach the user about the account. "
            "The user may skip a question; save what you get. When everything is saved, continue with what the user actually asked for.")


def handter(m, kall, instruksjoner=None):
    """Én JSON-RPC-melding inn, ett svar ut (None for varsler uten id)."""
    metode, id_, p = m.get("method"), m.get("id"), m.get("params") or {}
    if id_ is None:
        return None
    if metode == "initialize":
        ob = kall("GET", "/v1/onboarding", None, None) if instruksjoner is None else None
        antall = ((ob or {}).get("resultat") or {}).get("selskaper") if ob else None   # antall selskaper i datafila, så teksten følger nattbygget
        instr = INSTRUKSJONER.replace("450 000", f"{int(antall):,}".replace(",", " ") if antall else "450 000")
        instr += instruksjoner if instruksjoner is not None else onboarding_instruks(ob)
        return {"jsonrpc": "2.0", "id": id_, "result": {"protocolVersion": p.get("protocolVersion") or "2025-03-26", "capabilities": {"tools": {}},
                                                       "serverInfo": {"name": "firmasett", "title": "Firmasett – Norwegian company data", "version": VERSJON}, "instructions": instr}}
    if metode == "tools/list":
        return {"jsonrpc": "2.0", "id": id_, "result": {"tools": VERKTOY}}
    if metode == "tools/call":
        if kall is None:   # uten nøkkel; HTTP-laget svarer 401 før vi kommer hit, dette er for andre som bruker modulen
            return {"jsonrpc": "2.0", "id": id_, "error": {"code": -32001, "message": "authentication required"}}
        res = utfor(p.get("name"), p.get("arguments"), kall)
        import json
        return {"jsonrpc": "2.0", "id": id_, "result": {"content": [{"type": "text", "text": json.dumps(res, ensure_ascii=False, indent=1)}],
                                                       "isError": isinstance(res, dict) and res.get("status") == "feil"}}
    if metode == "ping":
        return {"jsonrpc": "2.0", "id": id_, "result": {}}
    return {"jsonrpc": "2.0", "id": id_, "error": {"code": -32601, "message": f"unknown method {metode}"}}
